I Read Stream with:
private Stream _Stream;
private Socket _Socket;//TCP Socket
private void ReadStream()
{
if (Guest)
{
var sizeBuffer = ReadBytes(2);//the size buffer is always 2
int size = sizeBuffer[1];
size |= (sizeBuffer[0] << 8);
var data = ReadBytes(size);
string payload = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
var tokens = SplitPayload(payload);
if (tokens[0] == "nick")
{
SetNick(tokens);
}
else
{
throw new ApplicationException("Set your nick first");
}
}
else if(!Guest)
{
var sizeBuffer = ReadBytes(2);
int size = sizeBuffer[1];
size |= (sizeBuffer[0] << 8);
var data = ReadBytes(size);
string payload = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
var tokens = SplitPayload(payload);
CheckToken(tokens);
}
if (encrypted == null)
{
encrypted = false;
byte[] sizebuffer = new byte[2];
var size = _Socket.Receive(sizebuffer);
byte[] data = new byte[size];
var datasize = _Socket.Receive(data);
if (data[0] == 0x01)
{
encrypted = true;
_Stream = new NetworkStream(_Socket, true);
var sslStream = new SslStream(_Stream, false);
serverCertificate = new X509Certificate2(Path, "");
sslStream.AuthenticateAsServer(serverCertificate);
_Stream = sslStream;
}
else
{
encrypted = false;
_Stream = new NetworkStream(_Socket, true);
}
}
}
I write to the stream with:
private void SendServerMsg(string[] arguments)
{
var msg = string.Join("\0", arguments);
byte[] data = Encoding.UTF8.GetBytes(msg);
byte[] sizeinfo = new byte[2];
sizeinfo[1] = (byte)data.Length;
sizeinfo[0] = (byte)(data.Length >> 8);
_Stream.Write(sizeinfo, 0, sizeinfo.Length);
_Stream.Write(data, 0, data.Length);
}
my Problem is now:
1. When I make a Breakpoint at the line
_Stream.Write(sizeinfo, 0, sizeinfo.Length);
and step through manualy all work. The TCP _Socket gets the correct bytes,
but with no breakpoint the server stucks in the line
var data = ReadBytes(size);
and the size is more than 5000 but I send not more than 15 bytes (for example: "nick\0test")
hear is the readBytes method
private byte[] ReadBytes(int count)
{
byte[] buffer = new byte[count];
for (var i = 0; i < count; i++)
{
var oneByte = _Stream.ReadByte();
if (oneByte == -1)
{
break;
}
buffer[i] = (byte)oneByte;
}
return buffer;
}
Related
Wrote some C# UWP code to encrypt files using the new encryption engine, and recently added code to make it be able to handle more bulky files by splitting the files up into parts and encrypting each part seperately since the libraries encrypt and decrypt functions won't take gigantic buffers. Now, it seems to be in some cases either outputting nothing to the file or giving a "system.exception" error in the Visual Studio debugger, which as you can imagine, isn't very helpful. Here's the code for this part of the program:
private async System.Threading.Tasks.Task encryptFile(StorageFile file, string key)
{
Loading.IsActive = true;
string HashAlgorithmName = HashAlgorithmNames.Md5;
HashAlgorithmProvider HashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmName);
CryptographicHash HashObject = HashProvider.CreateHash();
Windows.Storage.Streams.IBuffer keyAsBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf16BE);
HashObject.Append(keyAsBuffer);
Windows.Storage.Streams.IBuffer hashedKeyAsBuffer = HashObject.GetValueAndReset();
string hashedKey = CryptographicBuffer.EncodeToBase64String(hashedKeyAsBuffer);
key = hashedKey;
string algorithmName = SymmetricAlgorithmNames.AesEcbPkcs7;
SymmetricKeyAlgorithmProvider encryptionProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName);
Windows.Storage.Streams.IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(Encoding.ASCII.GetBytes(key));
CryptographicKey fullKey = encryptionProvider.CreateSymmetricKey(keyBuffer);
Stream fileStream = await file.OpenStreamForReadAsync();
byte[] fileBytes = ReadToEnd(fileStream);
Stream writeFileStream = await file.OpenStreamForWriteAsync();
IEnumerable<byte[]> splitFileBytes = ArraySplit(fileBytes, 100000000);
writeFileStream.Seek(0, SeekOrigin.Begin);
foreach (byte[] fileBytesFor in splitFileBytes)
{
Windows.Storage.Streams.IBuffer fileBuffer = fileBytesFor.AsBuffer();
Windows.Storage.Streams.IBuffer encryptedFileBuffer = CryptographicEngine.Encrypt(fullKey, fileBuffer, null);
Stream encryptedFileStream = encryptedFileBuffer.AsStream();
byte[] encryptedFileBytes = ReadToEnd(encryptedFileStream);
await writeFileStream.WriteAsync(encryptedFileBytes, 0, encryptedFileBytes.Length);
writeFileStream.Seek(0, SeekOrigin.End);
}
fileStream.Dispose();
writeFileStream.Dispose();
Loading.IsActive = false;
}
private async System.Threading.Tasks.Task decryptFile(StorageFile file, string key)
{
string HashAlgorithmName = HashAlgorithmNames.Md5;
HashAlgorithmProvider HashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmName);
CryptographicHash HashObject = HashProvider.CreateHash();
Windows.Storage.Streams.IBuffer keyAsBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf16BE);
HashObject.Append(keyAsBuffer);
Windows.Storage.Streams.IBuffer hashedKeyAsBuffer = HashObject.GetValueAndReset();
string hashedKey = CryptographicBuffer.EncodeToBase64String(hashedKeyAsBuffer);
key = hashedKey;
string algorithmName = SymmetricAlgorithmNames.AesEcbPkcs7;
SymmetricKeyAlgorithmProvider encryptionProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName);
Windows.Storage.Streams.IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(Encoding.ASCII.GetBytes(key));
CryptographicKey fullKey = encryptionProvider.CreateSymmetricKey(keyBuffer);
Stream fileStream = await file.OpenStreamForReadAsync();
byte[] fileBytes = ReadToEnd(fileStream);
Stream writeFileStream = await file.OpenStreamForWriteAsync();
Loading.IsActive = true;
writeFileStream.SetLength(0);
IEnumerable<byte[]> splitFileBytes = ArraySplit(fileBytes, 100000000);
writeFileStream.Seek(0, SeekOrigin.Begin);
foreach (byte[] fileBytesFor in splitFileBytes)
{
Windows.Storage.Streams.IBuffer fileBuffer = fileBytesFor.AsBuffer();
Windows.Storage.Streams.IBuffer decryptedFileBuffer = CryptographicEngine.Decrypt(fullKey, fileBuffer, null);
Stream decryptedFileStream = decryptedFileBuffer.AsStream();
byte[] decryptedFileBytes = ReadToEnd(decryptedFileStream);
await writeFileStream.WriteAsync(decryptedFileBytes, 0, decryptedFileBytes.Length);
writeFileStream.Seek(0, SeekOrigin.End);
}
fileStream.Dispose();
writeFileStream.Dispose();
Loading.IsActive = false;
}
public static byte[] StreamToByteArray(Stream inputStream)
{
byte[] bytes = new byte[375000000000000000];
using (MemoryStream memoryStream = new MemoryStream())
{
int count;
while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
{
memoryStream.Write(bytes, 0, count);
}
return memoryStream.ToArray();
}
}
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = 0;
if (stream.CanSeek)
{
originalPosition = stream.Position;
stream.Position = 0;
}
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if (stream.CanSeek)
{
stream.Position = originalPosition;
}
}
}
private IEnumerable<byte[]> ArraySplit(byte[] bArray, int intBufforLengt)
{
int bArrayLenght = bArray.Length;
byte[] bReturn = null;
int i = 0;
for (; bArrayLenght > (i + 1) * intBufforLengt; i++)
{
bReturn = new byte[intBufforLengt];
Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLengt);
yield return bReturn;
}
int intBufforLeft = bArrayLenght - i * intBufforLengt;
if (intBufforLeft > 0)
{
bReturn = new byte[intBufforLeft];
Array.Copy(bArray, i * intBufforLengt, bReturn, 0, intBufforLeft);
yield return bReturn;
}
}
i want to send string json over networkstream . code at client side
using (var ns = new NetworkStream(socket))
{
string json = JsonConvert.SerializeObject(listCfile, Formatting.Indented);
byte[] jsonbytes = Encoding.UTF8.GetBytes(json);
byte[] jsonLength = BitConverter.GetBytes(jsonbytes.Length);
ns.Write(jsonLength, 0, jsonLength.Length);
ns.Write(jsonbytes, 0, jsonbytes.Length);
}
jsonbytes was byte[988324]
At server side
using (var ns = new NetworkStream(socket))
{
byte[] byDataLength = new byte[4];
ns.Read(byDataLength, 0, 4);
int jsonLength = BitConverter.ToInt32(byDataLength, 0);
byte[] byData = new byte[jsonLength];
ns.Read(byData, 0, jsonLength);
File.WriteAllBytes("E:\\json.txt",byData);
}
byData was byte[988324]
But byData i received isn't same as jsonbytes i sent.
i need some helps.
Update! some times it works. ByData received is same as jsonbytes i sent
Some times it doesn't work :(
You can try using raw sockets to send and receive as well as using a memory stream and end-of-packet mechanism for unknown data lengths.
Below is a snippet of methods showing using raw sockets and buffering in a memory-stream till End-Of-Packet is detected.
protected const int SIZE_RECEIVE_BUFFER = 1024; /// Receive buffer size
protected const string EOF = "!#~*|"; /// End of packet string
MemoryStream _msPacket = new MemoryStream(); /// Memory stream holding buffered data packets
int _delmtPtr = 0; /// Ranking pointer to check for EOF
Socket _baseSocket;
public event EventHandler OnReceived;
// TODO: -
// Add methods to connect or accept connections.
// When data is send to receiver, send with the same EOF defined above.
//
//
public void RegisterToReceive()
{
byte[] ReceiveBuffer = new byte[SIZE_RECEIVE_BUFFER];
_baseSocket.BeginReceive
(
ReceiveBuffer,
0,
ReceiveBuffer.Length,
SocketFlags.None,
new AsyncCallback(onReceiveData),
ReceiveBuffer
);
}
private void onReceiveData(IAsyncResult async)
{
try
{
byte[] buffer = (byte[])async.AsyncState;
int bytesCtr = 0;
try
{
if (_baseSocket != null)
bytesCtr = _baseSocket.EndReceive(async);
}
catch { }
if (bytesCtr > 0)
processReceivedData(buffer, bytesCtr);
RegisterToReceive();
}
catch{ }
}
private void processReceivedData(byte[] buffer, int bufferLength)
{
byte[] eof = Encoding.UTF8.GetBytes(EOF);
int packetStart = 0;
for (int i = 0; i < bufferLength; i++)
{
if (buffer[i].Equals(eof[_delmtPtr]))
{
_delmtPtr++;
if (_delmtPtr == eof.Length)
{
var lenToWrite = i - packetStart - (_delmtPtr - 1);
byte[] packet = new byte[lenToWrite + (int)_msPacket.Position];
if (lenToWrite > 0)
_msPacket.Write(buffer, packetStart, lenToWrite);
packetStart = i + 1;
_msPacket.Position = 0;
_msPacket.Read(packet, 0, packet.Length);
try
{
if (OnReceived != null)
OnReceived(packet, EventArgs.Empty);
}
catch { }
_msPacket.Position = 0;
_delmtPtr = 0;
}
}
else
{ _delmtPtr = 0; }
}
if (packetStart < bufferLength)
_msPacket.Write(buffer, packetStart, bufferLength - packetStart);
if (_msPacket.Position == 0)
_msPacket.SetLength(0);
}
This can receive large length of data and is independent of length by the sender.
The methods above shows how to receive data only, so will have to include other methods for connect, accept, sending-data, etc on raw sockets.
In my application I wanted to implement profile pictures, so I started with a standard picture, which I converted to a byte array and then base64 string, however when the client requests the string from the server it doesnt fully arrive, the server reads the whole string from the database and sends it to the client, the client receives only a part of the string, this is the string(had to use pastebin): http://pastebin.com/ZmHhsZgG And this is the string the client receives: iVBORw0KGgoAAAANSUhEUgAAAEA
This is how the server gets it from the database:
public string GetPP(string user)
{
CONN = new MySqlConnection();
CONN.ConnectionString = Config.CONNSTRING;
string query = "select * from members where username='" + user + "'";
try
{
CONN.Open();
COMMAND = new MySqlCommand(query, CONN);
READER = COMMAND.ExecuteReader();
string p = null;
while (READER.Read())
{
return p = READER.GetString("profilepic");
}
return p;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "";
}
finally
{
CONN.Dispose();
}
}
then it sends it:
private void Do()
{
int requestCount = 0;
byte[] bytesFrom = new byte[20025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
Responder.Responder R = new Responder.Responder();
while ((true))
{
try
{
byte[] buffer = new byte[4];
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
buffer = new byte[4];
int readBytes = networkStream.Read(buffer, 0, 4);
if (readBytes == 0)
break;
int MessageSize = BitConverter.ToInt32(buffer, 0);
byte[] bufferreader = new byte[MessageSize];
readBytes = networkStream.Read(bufferreader, 0, MessageSize);
if (readBytes == 0)
break;
dataFromClient = Encoding.ASCII.GetString(bufferreader);
rCount = Convert.ToString(requestCount);
byte[] outbuffer = new byte[4];
serverResponse = R.Respond(dataFromClient);
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
outbuffer = new byte[4];
outbuffer = BitConverter.GetBytes(sendBytes.Length);
networkStream.Write(buffer, 0, 4);
networkStream.Flush();
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
}
}
Console.WriteLine("User Server >> " + "Client No:" + Convert.ToString(clNo) + " Stopped!");
}
And the client receives:
byte[] inbuffer = new byte[4];
buffer = new byte[4];
int readBytes = serverStream.Read(buffer, 0, 4);
int MessageSize = BitConverter.ToInt32(buffer, 0);
Console.WriteLine(Convert.ToString(MessageSize));
byte[] bufferreader = new byte[MessageSize];
readBytes = serverStream.Read(bufferreader, 0, MessageSize);
string dataFromServer = Encoding.ASCII.GetString(bufferreader);
if (dataFromServer.Contains("reauth"))
{
MessageBox.Show("Session Expired! Please Re-authenticate..");
this.Close();
}
else
{
richTextBox1.Text = dataFromServer; //used to see what it receives
MemoryStream mStream = new MemoryStream();
byte[] pData = Convert.FromBase64String(dataFromServer);
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
pictureBox1.Image = bm;
}
clientSocket.Close();
Thanks in advance
I think the data isn't fully read because the 'buffer' variable which you send as the length indicator is not initialized to an updated value. I guess what you wanted to send was:
serverResponse = R.Respond(dataFromClient);
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
outbuffer = new byte[4];
outbuffer = BitConverter.GetBytes(sendBytes.Length);
**networkStream.Write(outbuffer , 0, 4);**
networkStream.Flush();
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
NetworkStream.Read method returns the number of bytes successfully read.If you want to read whole data,you have to read several times.You can try follow codes:
private int read(NetworkStream ns, Byte[] data_buffer)
{
int result = -1;
const int kBufferSize = 1024 * 1024;
Byte[] buffer = new Byte[kBufferSize];
int read_size = 0;
int real_read_size = 0;
int read_length;
int total_length;
if (ns != null && data_buffer != null)
{
try
{
total_length = data_buffer.Length;
read_size = 0;
real_read_size = 0;
read_length = 0;
while (true)
{
read_size = kBufferSize <= (total_length - read_length) ? kBufferSize : total_length - read_length;
//todo:if (ns.CanRead)
real_read_size = ns.Read(buffer, 0, read_size);
if (real_read_size > 0)
{
Array.Copy(buffer, 0, data_buffer, read_length, real_read_size);
read_length += real_read_size;
//Console.WriteLine("net Read " + read_length.ToString() + " byte!");
if (read_length >= total_length)
{
result = 0;
break;
}
}
else
{
Console.WriteLine("net Read 0 byte!");
result = -1;
break;
}
}
}
catch (IOException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
}
}
return result;
}
I have this client and server code.
Client:
namespace ClientTest
{
internal class Program
{
private static TcpClient client;
private static NetworkStream stream;
private static void Main(string[] args)
{
string temp;
client = new TcpClient("192.168.1.2",5052);
stream = client.GetStream();
Console.WriteLine(client.SendBufferSize);
while ((temp = Console.ReadLine()) != "exit")
{
Send(temp);
}
Thread one=new Thread(()=> SendFile(new FileInfo(#"1.doc")));
one.Start();
Thread two=new Thread(()=> SendFile(new FileInfo(#"2.docx")));
two.Start();
// Console.ReadKey(true);
}
public static void SendFile(FileInfo file)
{
stream = client.GetStream();
byte[] id = BitConverter.GetBytes((ushort)1);
byte[] size = BitConverter.GetBytes(file.Length);
byte[] fileName = Encoding.UTF8.GetBytes(file.Name);
byte[] fileNameLength = BitConverter.GetBytes((ushort)fileName.Length);
byte[] fileInfo = new byte[12 + fileName.Length];
id.CopyTo(fileInfo, 0);
size.CopyTo(fileInfo, 2);
fileNameLength.CopyTo(fileInfo, 10);
fileName.CopyTo(fileInfo, 12);
stream.Write(fileInfo, 0, fileInfo.Length); //Размер файла, имя
byte[] buffer = new byte[1024 * 32];
int count;
long sended = 0;
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, count);
sended += count;
Console.WriteLine("{0} bytes sended.", sended);
}
stream.Flush();
}
private static void Send(string message)
{
byte[] id = BitConverter.GetBytes((ushort)0);
byte[] msg = Encoding.UTF8.GetBytes(message);
byte[] msgLength = BitConverter.GetBytes((ushort)msg.Length);
byte[] fileInfo = new byte[12 + msg.Length];
id.CopyTo(fileInfo, 0);
msgLength.CopyTo(fileInfo, 10);
msg.CopyTo(fileInfo, 12);
stream.Write(fileInfo, 0, fileInfo.Length);
stream.Flush();
}
}
}
Server:
namespace Server_Test
{
class Server
{
static void Main(string[] args)
{
Server serv = new Server();
}
private TcpListener listener { get; set; }
private NetworkStream stream { get; set; }
public Server()
{
listener = new TcpListener(IPAddress.Parse("192.168.1.2"), 5052);
listener.Start();
new Thread(ListenForClients).Start();
}
private void ListenForClients()
{
while (true)
{
TcpClient client = this.listener.AcceptTcpClient();
new Thread(HandleClient).Start(client);
}
}
private void HandleClient(object tcpClient)
{
TcpClient client = (TcpClient)tcpClient;
while (client.Connected)
{
Recieve(client);
}
}
private void Recieve(TcpClient client)
{
byte[] buffer = new byte[client.ReceiveBufferSize];
try
{
stream = client.GetStream();
int bytesRead = stream.Read(buffer, 0, 12);
if (bytesRead == 0) return;
ushort id = BitConverter.ToUInt16(buffer, 0);
long len = BitConverter.ToInt64(buffer, 2);
ushort nameLen = BitConverter.ToUInt16(buffer, 10);
stream.Read(buffer, 0, nameLen);
string fileName = Encoding.UTF8.GetString(buffer, 0, nameLen);
if (id == 1)
{
using (BinaryWriter writer = new BinaryWriter(new FileStream(fileName, FileMode.Create)))
{
int recieved = 0;
while (recieved < len)
{
bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);
recieved += bytesRead;
writer.Write(buffer, 0, bytesRead);
Console.WriteLine("{0} bytes recieved.", recieved);
}
}
Console.WriteLine("File length: {0}", len);
Console.WriteLine("File Name: {0}", fileName);
Console.WriteLine("Recieved!");
}
else
{
Console.WriteLine(fileName);
}
}
catch (Exception ex)
{
stream.Close();
client.Close();
Console.WriteLine(ex);
}
finally
{
stream.Flush();
}
}
}
}
The problem:i can't send 2 files in threads. If i send 1 file, server receives it and correctly saves.
What changes needed in this code to let client transfer 2 or more files and to let server receive it?
UDP. Added modified SendFile, but in doesn't work.
public static void SendFile(FileInfo file)
{
TcpClient client;
NetworkStream stream;
client = new TcpClient("192.168.1.2", 5052);
stream = client.GetStream();
byte[] id = BitConverter.GetBytes((ushort)1);
byte[] size = BitConverter.GetBytes(file.Length);
byte[] fileName = Encoding.UTF8.GetBytes(file.Name);
byte[] fileNameLength = BitConverter.GetBytes((ushort)fileName.Length);
byte[] fileInfo = new byte[12 + fileName.Length];
id.CopyTo(fileInfo, 0);
size.CopyTo(fileInfo, 2);
fileNameLength.CopyTo(fileInfo, 10);
fileName.CopyTo(fileInfo, 12);
stream.Write(fileInfo, 0, fileInfo.Length); //Размер файла, имя
byte[] buffer = new byte[1024 * 32];
int count;
long sended = 0;
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, count);
sended += count;
Console.WriteLine("{0} bytes sended.", sended);
}
}
On the client side, your two separate sending threads cannot share the same instance of client = new TcpClient("192.168.1.2",5052); to simultaneously send data. Each thread should have its own instance. Note, however, that it is fine for 2 client sockets to hit the same server-side IP:port simultaneously. It is just that the outbound port on the client-side has to be different between the 2 connections. When you create an additional outbound TCP connection on the client, the TcpClient will automatically use the next available outbound port.
For example, you could try something like the following:
internal class Program
{
private static void Main(string[] args)
{
SenderThreadClass stc1 = SenderThreadClass("192.168.1.2", 5052);
SenderThreadClass stc2 = SenderThreadClass("192.168.1.2", 5052);
Thread one = new Thread(()=> stc1.SendFile(new FileInfo(#"1.doc")));
one.Start();
Thread two = new Thread(()=> stc2.SendFile(new FileInfo(#"2.docx")));
two.Start();
}
}
public class SenderThreadClass
{
private TcpClient client;
private NetworkStream stream;
public SenderThreadClass(string serverIP, int serverPort)
{
client = new TcpClient(serverIP, serverPort);
stream = client.GetStream();
}
public void SendFile(FileInfo file)
{
byte[] id = BitConverter.GetBytes((ushort)1);
byte[] size = BitConverter.GetBytes(file.Length);
byte[] fileName = Encoding.UTF8.GetBytes(file.Name);
byte[] fileNameLength = BitConverter.GetBytes((ushort)fileName.Length);
byte[] fileInfo = new byte[12 + fileName.Length];
id.CopyTo(fileInfo, 0);
size.CopyTo(fileInfo, 2);
fileNameLength.CopyTo(fileInfo, 10);
fileName.CopyTo(fileInfo, 12);
stream.Write(fileInfo, 0, fileInfo.Length); //Размер файла, имя
byte[] buffer = new byte[1024 * 32];
int count;
long sended = 0;
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, count);
sended += count;
Console.WriteLine("{0} bytes sended.", sended);
}
stream.Flush();
}
}
I will get 3mins of delay at the start of the below program.but where as in hyper terminal it shows every data for every 2 secs.
Her is my below code.please let me know where i went wrong .How i can rectify this delay. any suggestion?
private void StartReceiving()
{
// coding part of receiving changed.
try
{
string IPStr = textBox1_IPaddress.Text.Trim();
string portStr = textBox2_Port.Text.Trim();
int port = Convert.ToInt32(portStr);
int bytesRead = 0;
byte[] buffer = new byte[9];
//------------------------------------------------------------------
IPAddress ipAddress = System.Net.IPAddress.Parse(IPStr);
//create server's tcp listener for incoming connection
try
{
textBox3.Visible = true;
client = new TcpClient();
client.Connect(IPStr, port);
ns = client.GetStream();
while (true)
{
if (ns.DataAvailable)
{
byte[] data = ReadNumberBytes(ns, 9);
ASCIIEncoding encoder = new ASCIIEncoding();
msg = encoder.GetString(data);
textBox3.AppendText(msg);
textBox3.AppendText("\n");
GetData(msg);
}
else
{
Thread.Sleep(4000);
byte[] data = ReadNumberBytes(ns, 9);
ASCIIEncoding encoder = new ASCIIEncoding();
msg = encoder.GetString(data);
GetData(msg);
}
}
client.Close();
}
catch (SocketException se)
{
//message box;
}
}
}
public static byte[] ReadNumberBytes(NetworkStream stream, int n)
{
byte[] buffer = new byte[n];
int bytesRead = 0;
int chunk;
while (bytesRead < n)
{
chunk = stream.Read(buffer, (int)bytesRead, buffer.Length - int)bytesRead);
if (chunk == 0)
{
// error out.
throw new Exception("Unexpected disconnect");
}
bytesRead += chunk;
}
return buffer;
}