gpt4 book ai didi

java - 在多线程环境中与 Java 服务器和 C# 客户端通信时出现管道损坏错误

转载 作者:行者123 更新时间:2023-12-01 11:08:23 25 4
gpt4 key购买 nike

我希望能找到任何帮助来解决我恼人的老问题。

我有一个使用 java 的 TCP 服务器程序和使用 c# 的客户端程序

这两者之间的数据包协议(protocol)仅由 4 字节长度和正文 ASCII 数据组成。

问题是 C# 客户端面临 FormatException,这是由于长度字节解析失败造成的。如果我从客户端查看错误,则客户端正在尝试解析正文中不是长度 header 的某个位置。但显然,服务器不会发送损坏的数据包。

同时,在服务器上,每当发生此类问题时,我都会发现“管道损坏”错误。

不幸的是,此错误并不总是发生,并且无法重现问题情况。这让我很难找到这个问题的确切原因

请参阅以下服务器端代码

public class SimplifiedServer {

private Map<InetAddress, DataOutputStream> outMap;
private Map<InetAddress,DataInputStream> inMap;

protected void onAcceptNewClient(Socket client) {
DataOutputStream out = null;
DataInputStream in = null;
try {
out = new DataOutputStream(client.getOutputStream());
in = new DataInputStream(client.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
outMap.put(client.getInetAddress(), out);
inMap.put(client.getInetAddress(), in);

}

public void writeToAll(String packet) {
outMap.forEach((key, out) -> {

try {
byte[] body = packet.getBytes("UTF-8");
int len = body.length;
if (len > 9999) {
throw new IllegalArgumentException("packet length is longer than 10000, this try will be neglected");
}

String lenStr = String.format("%04d%s", len, packet);
byte[] obuf = lenStr.getBytes();

synchronized (out) {
out.write(obuf);
out.flush();
}

} catch (IOException e) {
e.printStackTrace();
}
});

}


public void listenClient(Socket client) {
try {
DataOutputStream out = outMap.get(client.getInetAddress());
DataInputStream in = inMap.get(client.getInetAddress());

while (true) {

byte[] received = SimplePacketHandler.receiveLpControlerData(in);

byte[] lenBytes = new byte[4];

for( int i = 0 ; i < 4 ; i ++){
lenBytes[i] = in.readByte();
}

String lenString = new String(lenBytes);
int length = Integer.parseInt(lenString);
byte[] data = new byte[length];

for ( int i = 0 ; i < length ; i ++){
data[i] = in.readByte();
}

if ( data == null ){
System.out.println("NetWork error, closing socket :" + client.getInetAddress());
in.close();
out.close();
outMap.remove(client.getInetAddress());
inMap.remove(client.getInetAddress());
return;
}

doSomethingWithData(out, data);

}

} catch (NumberFormatException e) {
e.printStackTrace();
} catch ( Exception e ) {
e.printStackTrace();
} finally {
try {
System.out.println(client.getRemoteSocketAddress().toString() + " closing !!! ");
// remove stream handler from map
outMap.remove(client.getInetAddress());
inMap.remove(client.getInetAddress());

//close socket.
client.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}

}

这是客户端代码

 public class ClientSide
{
public TcpClient client;


public String ip;
public int port;
public NetworkStream ns;
public BinaryWriter writer;
public BinaryReader reader;

public Boolean isConnected = false;
public System.Timers.Timer t;
public String lastPacketSucceeded = String.Empty;


public ClientSide(String ip, int port)
{
this.ip = ip;
this.port = port;
client = new TcpClient();

}

public bool connect()
{
try
{
client.Connect(ip, port);
}
catch (SocketException e)
{
Console.WriteLine(e.ToString());
return false;
}


Console.WriteLine("Connection Established");

reader = new BinaryReader(client.GetStream());
writer = new BinaryWriter(client.GetStream());
isConnected = true;


return true;
}

public void startListen()
{
Thread t = new Thread(new ThreadStart(listen));
t.Start();
}

public void listen()
{

byte[] buffer = new byte[4];
while (true)
{

try
{
reader.Read(buffer, 0, 4);
String len = Encoding.UTF8.GetString(buffer);
int length = Int32.Parse(len);
byte[] bodyBuf = new byte[length];
reader.Read(bodyBuf, 0, length);

String body = Encoding.UTF8.GetString(bodyBuf);
doSomethingWithBody(body);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);

}

}

}

public void writeToServer(String bodyStr)
{
byte[] body = Encoding.UTF8.GetBytes(bodyStr);
int len = body.Length;
if (len > 10000)
{
Console.WriteLine("Send Abort:" + bodyStr);
}
len = len + 10000;
String lenStr = Convert.ToString(len);

lenStr = lenStr.Substring(1);

byte[] lengthHeader = Encoding.UTF8.GetBytes(lenStr);


String fullPacket = lenStr + bodyStr;
byte[] full = Encoding.UTF8.GetBytes(fullPacket);

try
{
writer.Write(full);
}
catch (Exception)
{
reader.Close();
writer.Close();
client.Close();

reader = null;
writer = null;
client = null;
Console.WriteLine("Send Fail" + fullPacket);

}
Console.WriteLine("Send complete " + fullPacket);

}
}

考虑到不可能重现问题,我猜这个问题是由多线程问题引起的。但我找不到任何进一步的线索来解决这个问题。

如果你们需要更多信息来解决这个问题,请告诉我。

任何帮助将不胜感激,提前致谢。

最佳答案

损坏的管道异常是由于关闭另一侧的连接而引起的。最有可能的是 C# 客户端存在错误,导致格式异常,从而导致它关闭连接,从而导致服务器端的管道损坏。请参阅what is the meaning of Broken pipe Exception? .

检查本次读取的返回值:

            byte[] bodyBuf = new byte[length];
reader.Read(bodyBuf, 0, length);

根据 Microsoft BinaryReader.Read 文档 https://msdn.microsoft.com/en-us/library/ms143295%28v=vs.110%29.aspx

[The return value is ] The number of bytes read into buffer. This might be less than the number of bytes requested if that many bytes are not available, or it might be zero if the end of the stream is reached.

如果它读取的长度字节少于长度字节,那么下次它将使用最后一条消息中间某处的数据来解析长度。

关于java - 在多线程环境中与 Java 服务器和 C# 客户端通信时出现管道损坏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32675917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com