我在编写socket聊天软件中遇到了一些问题,我写的代码如下:
public class KeyboardInputDemo {
public static void main(String[] args) throws IOException {
BufferedReader bufr = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
line = bufr.readLine();
System.out.println(line);
new Thread(new Sender2()).start();
new Thread(new recver2()).start();
}
}
class Sender2 implements Runnable {
public void run() {
try {
System.out.println("please input");
DatagramSocket ds = new DatagramSocket(10001);
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = null;
String line = null;
byte[] buf = null;
BufferedReader bufr = new BufferedReader(new InputStreamReader(
System.in));
while ((line = bufr.readLine()) != null) {
buf = line.getBytes();
dp = new DatagramPacket(buf, buf.length, ia, 10002);
ds.send(dp);
}
} catch (Exception e) {
}
}
}
class recver2 implements Runnable {
public void run() {
try {
DatagramSocket ds = new DatagramSocket(10002);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
while (true) {
ds.receive(dp);
String data = new String(dp.getData());
System.out.println(data);
}
} catch (Exception e) {
System.out.println("bbbbbbbbbbbbbbbbbbbbb");
}
}
}
现在的这程序是能够运行没有问题,但是在我写的时候如果把while循环拿出来写成如下代码。
class recver2 implements Runnable {
public void run() {
while (true) {
try {
DatagramSocket ds = new DatagramSocket(10002);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
String data = new String(dp.getData());
System.out.println(data);
} catch (Exception e) {
System.out.println("bbbbbbbbbbbbbbbbbbbbb");
}
}
}
}
换成如下代码就会出现问题,我们知道ds.receive(dp);是等待机制,就是说如果没有收到数据是不会执行,但是在发送端发送数据两次之后,接收端就会报错,这是为什么,代码有点多,希望能谁能给我解释一下这是为什么?
|