c# - Client Socket not getting reponse bytes in .NET -
i creating , sending message on server socket , not getting response in return , know possible reasons same. below sample code client socket
static void main() { int _dcpport = 9090; iphostentry iphostinfo = dns.gethostentry("hostname"); console.writeline("got ip host info" , iphostinfo.tostring ()); ipaddress ipaddress = iphostinfo.addresslist[0]; console.writeline("got ip hadress info"); //end point of host socket connected ipendpoint remotedapendpoint = new ipendpoint(ipaddress, _dcpport); // create clientsocket connects host socket clientdap = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); clientdap.connect(remotedapendpoint); console.writeline("client socket connected remote end point"); #region input variables string requeststring = "hello"; string responsestring = ""; byte[] requestbyte = system.text.encoding.utf8.getbytes(requeststring); byte[] responsebyte = new byte[1024]; stringbuilder messagebuilder = new stringbuilder(); int byteresult = 0; #endregion try { //sending string bytes on socket console.writeline("sending input " + requeststring); clientdap.send(requestbyte); } catch (socketexception ex) { console.writeline(ex.message); } try { //recieving response bytes byteresult = clientdap.receive(responsebyte, clientdap.available, socketflags.none); console.writeline("recieved {0} bytes response remote end point" , byteresult); if (clientdap.connected) { responsestring = encoding.utf8.getstring(responsebyte); messagebuilder.append(responsestring); } } catch (socketexception ex) { console.writeline(ex.message); } clientdap.shutdown(socketshutdown.both); clientdap.disconnect(true); string sresult = messagebuilder.tostring(); console.writeline(sresult); }
i not getting bytes when call socket.recieve() , reasons why such happening ?
from socket.send
:
there no guarantee data send appear on network immediately. increase network efficiency, underlying system may delay transmission until significant amount of outgoing data collected. successful completion of send method means underlying system has had room buffer data network send
which means data may not have arrived @ server yet when call send
has completed. let alone server has had time process data , return response.
and yet code charges straight ahead try receive server's response. isn't unreasonable, in , of itself. call receive
would have blocked until had received some data if had specified size of buffer, rather using available
, happily return 0
if there's no data yet available. receive
call asking 0
bytes , that's how many you're being given.
so change line
byteresult = clientdap.receive(responsebyte, 1024, socketflags.none);
(or better yet, introduce constant and/or use responsebyte.length
or switch overload don't explicitly specify how many bytes want)
Comments
Post a Comment