所以我从互联网上获得了这个简单的udp客户端/服务器代码,并且它可以工作。但是,当我输入比我之前输入的东西更短的东西时,我会剩下剩下的字符。例如,如果我先输入:
kitty
然后输入:
cat
第二个印刷品读作:
catty
我一直在寻找有类似问题的其他人,其中大部分似乎都是通过清除字节数组来解决的。但是,如果我尝试实现他们的答案,它不能解决我的问题。我需要做什么,并且(可能更重要的是)代码应该去哪里?这是代码:
客户端:
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 20700);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
服务器:
import java.io.*;
import java.net.*;
import java.util.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(21200);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
答案 0 :(得分:7)
您不需要清除字节数组,但需要通过getLength()
方法在接收后通知DatagramPacket的长度;例如:
new String(packet.getData(), packet.getOffset(), packet.getLength());
您在服务器中正确地执行了此操作,但未在客户端中执行此操作。
您还需要在调用receive()
之前重置长度。否则,DatagramPacket
将继续缩小到目前为止收到的最小数据包的长度。