一个项目,需要JAVA的Socket客户端转换为C#的Socket客户端,使用的是短连接。
首先,java客户端代码如下:
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);
...
一开始转换C#代码使用最简单的同步方式,对应代码差异如下:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
socket.ReceiveTimeout = respTimeout;
...
socket.Send(allBty);
//接收返回的字节流
byte[] buffer = new byte[1024];
int bytesRec = 0;
MemoryStream memStream = new MemoryStream();
while ((bytesRec = socket.Receive(buffer)) >0)//结果第一次Receive接收消息正确,第二次接收就报错:由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。去掉while循环,不会报错,但即使数据量未超过1024,服务端接收并返回了消息,客户端的接收也很不稳定,有时能收到有时收不到;如果超过1024,数据接收不全
{
bytesRec = socket.Receive(buffer);
memStream.Write(buffer, 0, bytesRec);
}
byte[] bb = new byte[4];
memStream .Read(bb, 0, 4);
...
分析:java采取流的方式进行读取,可能是java一次性发送后断开了socket,导致C#不能多次接收,尝试C#也以流的方式接收。
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);
...
经测试,通信正常稳定。