I'm trying to read from socket for the first time, then abort the thread which handles it and then reread again. The weird part here is that sometimes it works and sometimes it doesn't.
client:
private void startSend()
{
Image f;
ms = new MemoryStream();
while (true)
{
f = GetDesktopImage();
f.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
bmpBytes = (ms.ToArray());
SendVarData(client.Client, bmpBytes);
count++;
ms.SetLength(0);
}
}
private int SendVarData(Socket s, byte[] data)
{
total = 0;
int size = data.Length;
int dataleft = size;
int sent;
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);
while (total < size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}
i call the start send in a thread which always keep running in the background.
server code:
MemoryStream ms;
byte[] data;
public void startListening()
{
while (true)
{
try
{
data = ReceiveVarData(client.Client);
ms = new MemoryStream(data);
theImage.Image = Image.FromStream(ms);
count++;
} catch {}
}
}
private static byte[] ReceiveVarData(Socket s)
{
int total = 0;
int recv;
byte[] datasize = new byte[4];
recv = s.Receive(datasize, 0, 4, 0);
int size = BitConverter.ToInt32(datasize, 0);
int dataleft = size;
byte[] data = new byte[size];
while (total < size)
{
recv = s.Receive(data, total, dataleft, 0);
if (recv == 0) break;
total += recv;
dataleft -= recv;
}
return data;
}
It works great as i said first time, but than when i try to close the thread on the second form close
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
th.Abort();
}
and try to read again I'm just getting an error at this line
byte[] data = new byte[size];
Error:
Arithmetic operation resulted in an overflow
tried to print size value and it was something like -2522561418...
of course i restart the thread again on the form opening
th= new Thread(new ThreadStart(startListening));
th.Start();
You can't "reread" data from a socket that was read already. Why would you think this is possible? I don't understand the line of thought behind it.
Thread.Abort is evil and can't be used. As long as your code contains a call to that method your code is invalid and must be changed.
Abort can't abort IO anyway. The abort can happen before or after the network read. I guess that explains why sometimes "rereading" works - because the data was not read before.
Probably you should have a thread running for the duration of the connection. That thread should read everything that comes in and place it into a data structure for later retrieval. For example, a Queue<Image>.
In fact I'd strongly advise you to delete all this socket code and use WCF or HTTP. These protocols handle a lot of details for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With