A project that requires a Java socket client to be converted to a C # socket client, using a short connection.
First, the Java client code is as follows:
Socket socket = new socket ();
Socket.connect (New Inetsocketaddress (IP, port), timeout);
Socket.setsotimeout (resptimeout);
OutputStream outputstream = null;
InputStream is = null;
OutputStream = Socket.getoutputstream ();
...
byte[] allbty = new Byte[bytecount];
Outputstream.write (allbty);
Outputstream.flush ();
is = Socket.getinputstream ();
byte[] bb = new BYTE[4];
Is.read (BB, 0, 4);
...
The first conversion of C # code using the simplest synchronization method, the corresponding code differences are as follows:
Socket socket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
Socket. Connect (New IPEndPoint (Ipaddress.parse (IP), port));
Socket. ReceiveTimeout = Resptimeout;
...
Socket. Send (allbty);
Receive the returned byte stream
byte[] buffer = new byte[1024];
int bytesrec = 0;
MemoryStream memstream = new MemoryStream ();
while (Bytesrec = socket. Receive (buffer)) >0)//Results The first receive message is correct, and the second receives an error: The connection attempt failed because the connecting party did not respond correctly after a period of time or the connected host was unresponsive. Remove the while loop, no error, but even if the data volume is not more than 1024, the server receives and returns the message, the client receives is also very unstable, sometimes receive is sometimes not received, if more than 1024, the data received is not full
{
Bytesrec = socket. Receive (buffer);
Memstream.write (buffer, 0, BYTESREC);
}
byte[] bb = new BYTE[4];
Memstream. Read (BB, 0, 4);
...
Analysis: Java takes a stream to read, it may be Java one-time send after disconnecting the socket, resulting in C # can not be received many times, try C # also streamed to receive.
TcpClient TcpClient = new TcpClient ();
Tcpclient.connect (Ipaddress.parse (IP), port);
Tcpclient.receivetimeout = Resptimeout;
NetworkStream sendsteam = null;
NetworkStream receivesteam = null;
...
Sendsteam = Tcpclient.getstream ();
Sendsteam.write (allbty, 0, allbty.length);
Sendsteam.flush ();
Receivesteam = Tcpclient.getstream ();
bb = new BYTE[4];
Receivesteam.read (BB, 0, 4);
...
After testing, the communication is normal and stable.
Java and. NET Socket Conversion error logging