我打印出来都是相同的,这个字符串比较为什么会是False?
我写的就是UDP协议的很简单的本机两个端口下的网络通信,一直不能理解为什么在类UDPSender中接收到UDPReciver发送的ACK消息时,receiverRes.equals("ACK")的返回值是False,真的是不理解啊,我特意还打印了receiverRes的值,就是ACK,错在哪了,求指教
我不知道大家看懂我的代码没有,就是发送方向接收方发送字符,接收方正确接收后,会发送ACK给接收方,接收方收到ACK后才能确认,实现的是停等协议!
import java.net.*;
import java.util.*;
public class UDPReciver{
public static void main(String[] args) throws Exception{
DatagramSocket ds = null;
DatagramPacket dp1 = null;
DatagramPacket dp2 = null;
byte[] buf1 = new byte[1024];
byte[] buf2 = new byte[1024];
ds = new DatagramSocket(9000);
while(true){
System.out.println("开始接收数据");
dp1 = new DatagramPacket(buf1,1024);
ds.receive(dp1);
String sendWhat =new String(buf1);
System.out.println("请进行以下选择:a.成功接收该字符 b.丢失 c.无反应、超时");
Scanner scan = new Scanner(System.in);
String choose = scan.next();
if(choose.equals("a")){
System.out.println("成功接收" + sendWhat);
String ACKSend = new String("ACK");
buf2 = ACKSend.getBytes();
dp2 = new DatagramPacket(buf2,ACKSend.length(),InetAddress.getByName("localhost"),3000);
ds.send(dp2);
System.out.println("dada");
}
if(choose.equals("b")){
String NAKSend = new String("NAK");
buf2 = NAKSend.getBytes();
dp2 = new DatagramPacket(buf2,NAKSend.length(),InetAddress.getByName("localhost"),3000);
ds.send(dp2);
}
if(choose.equals("c")){
System.out.println("超时,请重传!");
}
}
}
}
import java.util.*;
import java.net.*;
import java.io.*;
public class UDPSender{
//private static final int TIMEOUT=3000;
public static void main(String[] args) throws Exception{
int TIMEOUT=3000;
DatagramSocket ds = null;
DatagramPacket dp1 = null;
DatagramPacket dp2 = null;
byte[] buf1 = new byte[1024];
byte[] buf2 = new byte[1024];
ds = new DatagramSocket(3000);
System.out.println("开始发送数据");
int i = 0;
String send =new String();
while(true){
Scanner scan = new Scanner(System.in);
System.out.println("请输入传送的字符");
send = "";
send += i;
send += scan.next();
buf1 = send.getBytes();
dp1 = new DatagramPacket(buf1,send.length(),InetAddress.getByName("localhost"),9000);
ds.send(dp1);
//设置receive()方法的最长阻塞时间
ds.setSoTimeout(TIMEOUT);
dp2 = new DatagramPacket(buf2,1024);
try{
ds.receive(dp2);
String receiverRes = new String(buf2);
System.out.println(receiverRes);
System.out.println(receiverRes.equals("ACK"));
//System.out.println("aaaaa");
if(receiverRes.equals("ACK")){
System.out.println("aaaaa");
i = (i+1) % 2;
//System.out.println(i);
continue;
}
else if(receiverRes.equals("NAK")){
ds.send(dp1);
}
}catch(InterruptedIOException e){
ds.send(dp1);
}
//else{
//ds.send(dp1);
//System.out.println(i);
//}
}
}
}
破坏zero
10 years, 8 months ago
Answers
byte[] buf2 = new byte[1024];
...
String receiverRes = new String(buf2);
System.out.println(receiverRes);
System.out.println(receiverRes.equals("ACK"));
因为你这里直接用buf2,new String了,所以此时
receiverRes
其实是除了你接收到的和数据外,后面还多加了很多个空字符。总长度就是buf2的长度。两个长度和内容都不同的字符串,怎么可能相同呢
bluesad
answered 10 years, 8 months ago