C # re-read from socket
I am trying to read from a socket for the first time and then interrupt the thread that is processing it and then re-read again. The weird part here is that sometimes it works and sometimes it doesn't.
customer:
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 am calling start dispatch on a thread that is always 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 fine as I said the first time, but than when I try to close the stream on the second form, close
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
th.Abort();
}
and try reading again. I just get an error on this line
byte [] data = new byte [size];
Mistake:
Arithmetic operation overflowed
tried to print the value size
and it was something like -2522561418
...
of course i restart the thread again when i open the form
th= new Thread(new ThreadStart(startListening));
th.Start();
You cannot "re-read" data from a socket that has already been read. Why do you think this is possible? I don't understand what the thought is behind this.
Thread.Abort is evil and cannot be used. As long as your code contains a call to this method, your code is invalid and must be changed.
Abort
cannot interrupt IO. Cancellation can occur before or after the network read. I think this explains why sometimes "rereading" works because the data has not been read before.
You should probably have a thread running for the duration of the connection. This stream should read everything that comes in and put it into a data structure for later retrieval. For example, a Queue<Image>
.
In fact, I highly recommend that you remove all of this socket code and use WCF or HTTP. These protocols handle a lot of detail for you.
source to share