本帖最后由 华行天下 于 2013-10-18 10:22 编辑
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
class Send implements Runnable{
private DatagramSocket ds;
public Send(DatagramSocket ds){
this.ds=ds;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while((line=bufr.readLine())!=null)
{
if("886".equals(line))
break;
byte[] buf=line.getBytes();
DatagramPacket dp=
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.102"),10003);
ds.send(dp);
}
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException("发送端失败");
}
}
}
class Rece implements Runnable{
private DatagramSocket ds;
public Rece(DatagramSocket ds){
this.ds=ds;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
byte[] buf=new byte[1024];
while(true){
DatagramPacket dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::"+data);
}
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException("数据读取失败");
}
}
}
public class ChatDemo {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
DatagramSocket sendSocket=new DatagramSocket();
DatagramSocket receSocket=new DatagramSocket(10003);
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}
}
为什么程序运行后,只能和自己发一次程序就不能再发了啊? |