c# - Stream was not readable is caused when use readbinary -
i trying send value socket .so have 2 parts in project client , server .
the client sends value server using code :
networkstream networkstream = socketforserver.getstream(); system.io.binarywriter binarywriter = new system.io.binarywriter(networkstream); //------ int messagesource = 0; int messagedesitination = 0; int interlockingid = 0; int trackid = 0; int trainid = 2; int direction = 0; int messagetype = 0; int informationtype = 0; int datetime = 0; foreach (sensor leftsensorlist in leftsensor) { binarywriter.write(messagesource); binarywriter.write(messagedesitination); binarywriter.write(interlockingid); binarywriter.write(trackid); binarywriter.write(trainid); binarywriter.write(direction); binarywriter.write(messagetype); binarywriter.write(informationtype); binarywriter.write(datetime); binarywriter.flush(); binarywriter.close(); thread.sleep(4000); }
in server part should read binary values :
static void listeners() { socket socketforclient = tcplistener.acceptsocket(); if (socketforclient.connected) { networkstream networkstream = new networkstream(socketforclient); while (true) { list<int> variables = new list<int>(); using (var reader = new binaryreader(networkstream)) { int messagesource = reader.readint32(); int messagedesitination = reader.readint32(); int interlockingid = reader.readint32(); int trackid = reader.readint32(); int trainid = reader.readint32(); int direction = reader.readint32(); int messagetype =reader.readint32(); int informationtype = reader.readint32(); int datetime = reader.readint32(); reader.close(); } } }
so when client send value can value in server part first time ,when client sends values server got error :
stream not readable.
why ?
this caused because binaryreader assumes owns stream , closes when uses it. if you're using 4.5 can use overload http://msdn.microsoft.com/en-us/library/gg712804(v=vs.110).aspx
it should you.
static void listeners() { socket socketforclient = tcplistener.acceptsocket(); if (socketforclient.connected) { networkstream networkstream = new networkstream(socketforclient); while (true) { list<int> variables = new list<int>(); //hint : line using (var reader = new binaryreader(networkstream, encoding.default, true)) { int messagesource = reader.readint32(); int messagedesitination = reader.readint32(); int interlockingid = reader.readint32(); int trackid = reader.readint32(); int trainid = reader.readint32(); int direction = reader.readint32(); int messagetype =reader.readint32(); int informationtype = reader.readint32(); int datetime = reader.readint32(); reader.close(); } } } }
Comments
Post a Comment