我正在使用UDP编写客户端 - 服务器聊天程序。如果客户端或服务器发送消息,并且它们发送的下一条消息比它们发送的上一条消息短,则较长消息的一部分将放在较短消息的末尾。这是我第一次使用UDP而且我不知道是什么导致这种情况,我使用TCP制作了一个类似的程序并且没有这个问题。
客户看到的内容:
客户:你好,你好吗?
服务器:我很好,谢谢,你呢?
客户:很好
服务器看到了什么:
客户:你好,你好吗?
服务器:我很好,谢谢,你呢?
客户:太好了,你好吗?
我的服务器代码:
public class ChatServer implements Runnable
{
public static void main(String[] args) throws Exception
{
new Thread(new ChatServer()).start();
}
@Override
public void run()
{
try
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[65508];
byte[] sendData = new byte[65508];
System.out.println("Enter a username: ");
String serverUsername = inFromUser.readLine();
System.out.println("Send message...");
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String clientSentence = new String(receivePacket.getData());
System.out.println(clientSentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.print("Me: ");
String serverSentence = serverUsername + ": " + inFromUser.readLine();
sendData = serverSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
catch (IOException ex)
{
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我的客户代码:
public class ChatClient
{
public static void main(String[] args) throws Exception
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
try (DatagramSocket clientSocket = new DatagramSocket())
{
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[65508];
byte[] receiveData = new byte[65508];
System.out.println("Enter a username: ");
String clientUsername = inFromUser.readLine();
System.out.println("Send message...");
while(true)
{
System.out.print("Me: ");
String clientSentence = clientUsername + ": " + inFromUser.readLine();
sendData = clientSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String serverSentence = new String(receivePacket.getData());
System.out.println(serverSentence);
}
}
catch(Exception e)
{
e.getMessage();
}
}
}
答案 0 :(得分:0)
接收数据包最初为空终止。 它充满了网络数据。 在每次构造clientSentence之后,您需要告诉字符串要读取多少字节或将receiveData清零。使用数据包的长度是解决此问题的正确方法。
变化:
String clientSentence = new String(receivePacket.getData());
要:
String clientSentence = new String(receivePacket.getData() ,0 , receivePacket.getLength());