这个问题一直在破坏我的头脑,我似乎无法弄清楚为什么它不会起作用。 所以我运行客户端/服务器程序,让客户端通过JOptionPane输入某个字符串,然后将其发送到服务器。服务器有一个字符串数组,它检查从客户端接收的字符串是否等于数组中的一个字符串。但是,比较似乎失败了。如果有人能告诉我为什么会遇到这个问题,我会很高兴。
下面是我的服务器的代码,其中if语句在for循环中失败,而数组(usrs):
String [] usrs = {"Hassan","Jimmy","Bob","Kevin"};
DatagramSocket skt = null;
try {
skt = new DatagramSocket(2002);
byte [] buffer = new byte [1000];
String okay = "OK";
while(true) {
System.out.println("Inside loop");
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
skt.receive(request);
String userName = (new String(request.getData()));
System.out.println(userName);
for (int i=0; i < usrs.length; i++) {
System.out.println(usrs[i]);
//if user exists in list of verified users,we send the RSA encrypted AES Key using that user's public key which we receive from the user
if (userName.equals(usrs[i])) {
System.out.println("Inside If");
byte [] okayMsg = okay.getBytes();
DatagramPacket reply = new DatagramPacket(okayMsg,okayMsg.length,request.getAddress(),request.getPort());
skt.send(reply);
skt.close();
}
}
}
以下是我的客户代码:
try {
skt = new DatagramSocket();
String userName = JOptionPane.showInputDialog(null,"Please enter your username");
byte [] b = userName.getBytes();
InetAddress host = InetAddress.getByName("localhost");
int serverSocket = 2002;
DatagramPacket request = new DatagramPacket(b,b.length,host,serverSocket);
skt.send(request);
byte [] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
skt.receive(reply);
String replyData = new String(reply.getData());
System.out.println(replyData);
skt.close();
} catch(Exception e) {
e.printStackTrace();
};
这是输出:
Inside loop
Hassan
Hassan
Jimmy
Bob
Kevin
Inside loop
答案 0 :(得分:2)
构建DatagramPacket
时需要检查replyData
的长度:
String replyData = new String(reply.getData(), 0, reply.getLength());
否则假设reply.getData()
返回的整个数组包含字符串数据,但不一定如您所见。
使用显式字符编码也是明智的,因为在客户端和服务器JVM上由于不匹配的默认字符编码而不会出现奇怪的行为:
byte [] b = userName.getBytes(StandardCharsets.UTF_8);
和
String replyData = new String(..., StandardCharsets.UTF_8);
答案 1 :(得分:1)
显然打印request.getLength()
解决了问题。
收到的响应填充为响应缓冲区的大小。