multithreading - c# reread from socket -
i'm trying read socket first time, abort thread handles , reread again. weird part here works , 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 start send in thread keep running in 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 said first time, when try close thread on second form close
private void window_closing(object sender, system.componentmodel.canceleventargs e) { th.abort(); }
and try read again i'm getting error @ line
byte[] data = new byte[size];
error:
arithmetic operation resulted in overflow
tried print size
value , -2522561418
...
of course restart thread again on form opening
th= new thread(new threadstart(startlistening)); th.start();
you can't "reread" data socket read already. why think possible? don't understand line of thought behind it.
thread.abort evil , can't used. long code contains call method code invalid , must changed.
abort
can't abort io anyway. abort can happen before or after network read. guess explains why "rereading" works - because data not read before.
probably should have thread running duration of connection. thread should read comes in , place data structure later retrieval. example, queue<image>
.
in fact i'd advise delete socket code , use wcf or http. these protocols handle lot of details you.
Comments
Post a Comment