我目前正在使用一种可靠的UDP协议的Java实现,可以在这里找到。该项目没有任何教程,所以我很难确定问题所在。
我已经建立了一个客户端和服务器。服务器运行在localhost:1234上,客户端运行在localhost:1235上。首先建立服务器,然后循环监听连接。
我已经建立了一个客户端和服务器。服务器运行在localhost:1234上,客户端运行在localhost:1235上。首先建立服务器,然后循环监听连接。
try {
ReliableSocket clientSocket = server.socket.accept();
InetSocketAddress clientAddress = (InetSocketAddress) clientSocket.getRemoteSocketAddress();
Logger.getLogger("ServerConnectionListener").info("New Connection from "+
clientAddress.getHostName()+":"+clientAddress.getPort()+" Processing...");
LessurConnectedClient client = new LessurConnectedClient(clientSocket);
ClientCommunicationSocketListener listener = new ClientCommunicationSocketListener(this, client);
clientSocket.addListener(listener);
} catch (Exception e) {
e.printStackTrace();
}
建立连接时,会为该套接字创建一个事件监听器 -
class ClientCommunicationSocketListener implements ReliableSocketListener {
ServerConnectionListener connectionListener;
LessurConnectedClient client;
public ClientCommunicationSocketListener(ServerConnectionListener connectionListener, LessurConnectedClient client){
this.connectionListener = connectionListener;
this.client = client;
}
@Override
public void packetReceivedInOrder() {
connectionListener.server.handlePacket(client);
}
@Override
public void packetReceivedOutOfOrder() {
connectionListener.server.handlePacket(client);
}
}
当一个数据包被接收后,它会被传递给server.handlePacket函数进行处理,并打印出调试信息“Packet Received!”。
我的客户端连接到服务器的方法如下 -
LessurClient client = new LessurClient();
InetSocketAddress a = (InetSocketAddress) server.getSocket().getLocalSocketAddress();
Logger.getLogger("client-connector").info("Trying to connect to server "+
a.getAddress().toString()+":"+
a.getPort());
client.connect(a.getAddress(), a.getPort());
// LessurClient.connect
public void connect(InetAddress address, int port){
try {
socket = new ReliableSocket(address, port, InetAddress.getLocalHost(), 1235);
isConnected = true;
Logger.getLogger("LessurClient").info("Connected to server "+address.getHostAddress()+":"+port);
} catch (IOException e) {
e.printStackTrace();
}
}
我已经将代码链接,所以当我按下“Z”键时,它会发送一个数据包到服务器,如下所示 -
public void sendPacket(GamePacket packet){
if(!isConnected){
Logger.getLogger("LessurClient").severe("Can't send packet. Client is not connected to any server.");
return;
}
try {
OutputStream o = socket.getOutputStream();
o.write(packet.getData());
o.flush();
Logger.getLogger("LessurClient").info("Sending Packet with data \""+packet.getData()+"\" to server "+socket.getInetAddress().toString()+":"+socket.getPort());
} catch (IOException e) {
e.printStackTrace();
}
}
我的问题是,在发送了32个数据包后,服务器不再接收数据包,而在发送了64个数据包后,服务器崩溃。我已经调查了代码,看起来是与数据包没有从接收队列中删除有关,因为当我将ReliableSocket.java:1815中的_recvQueueSize变量从32更改为40时,现在可以发送40个数据包而没有出现问题。
能否有人帮助我识别这个问题?我整天都在看代码。