Transmitting/receiving a bitmap with .NET Sockets C++/CLI -
im programming schoolproject internet/multiplayer based drawing game. need program picturebox actual servers one.
first of im using .net tcp client , listener works(im sending , receiving strings). have 2 static classes represents server , client.
my basic idea convert bmp picturebox in byte[] transmitt binaryreader thru networkstream.
on other side received byte[] converted bmp , goes picturebox.
here my 2 functions:
void server::sendbmp(bitmap^ bmp){ array<byte>^bytes = gcnew array<byte>(256); binarywriter^ bw = gcnew binarywriter(stream); memorystream^ ms = gcnew memorystream(); bmp->save(ms,system::drawing::imaging::imageformat::bmp); //conversion bmp byte[] bytes = ms->toarray(); bw->write(bytes);} bitmap^ server::receivebmp(void){ array<byte>^buffer = gcnew array<byte>(10000); binaryreader^ br = gcnew binaryreader(stream); bitmap^ bmp = gcnew bitmap(1500,612); buffer = br->readbytes(10000); memorystream^ ms = gcnew memorystream(buffer); // conversion byte[] bmp bmp->fromstream(ms); return bmp;}
im getting "system.argumentexception" error.
im using synchronous tcp sockets. right way im doing this?
stack trace:
server::receivebmp() line 105 + 0x8 bytes drawmything::myform::streamimg() line 2774 + 0x6 bytes
line 105:
bmp->fromstream(ms); //from server::receiveimg()
line 2774:
private: static void streamimg(void){ while(1){ if(status==1){ //if server bitmap = server::receivebmp(); //line 2774 }else{ client::sendbmp(bitmap); } } }
btw im calling streamimg function thread:
thread^ imgstreamthread = gcnew thread(gcnew threadstart(myform::streamimg)); imgstreamthread->start();
buffer = br->readbytes(10000);
the bug in code here. should have made little uncomfortable writing 10000 here. how did come that? why not 20000? never use "magic number" when write code. produces bug.
so write then? cannot large, call hang. cannot small, won't read enough bytes in bitmap , program fail found out. must exact number of bytes in bitmap.
that's chicken-and-egg problem, how know? cannot know, transmitter has help. has send size first:
void server::sendbmp(bitmap^ bmp){ //... bytes = ms->toarray(); bw->write(bytes->length); bw->write(bytes); }
now simple:
bitmap^ server::receivebmp(void) { binaryreader^ br = gcnew binaryreader(stream); int length = br->readint32(); array<byte>^ buffer = br->readbytes(length); system::diagnostics::debug::assert(buffer->length == length); memorystream^ ms = gcnew memorystream(buffer); return safe_cast<bitmap^>(image::fromstream(ms)); }
Comments
Post a Comment