package cn.net.udp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ChatUDP {
public static void main(String[] args) throws Exception {
DatagramSocket ds=new DatagramSocket(10000);
new Thread(new Rece(ds)).start();
InetAddress address=InetAddress.getLocalHost();
new Thread(new Send(ds, address, 10001));
}
}
/*发送端
*/
class Send implements Runnable{
private DatagramSocket ds;
private InetAddress address;
private int point;
public Send(DatagramSocket ds,InetAddress address,int point) {
this.ds=ds;
this.address=address;
this.point=point;
}
@Override
public void run() {
//键盘输入
BufferedReader bufr=new BufferedReader(
new InputStreamReader(System.in));
String line=null;
try {
while((line=bufr.readLine())!=null){
//定义缓存
byte[] buf=line.getBytes("GBK");
DatagramPacket dp=new DatagramPacket(buf, buf.length,address,point);
ds.send(dp);
System.out.println("me::"+line);
if("over".equals(line)||"886".equals(line))
break;
}
} catch (Exception e) {
throw new RuntimeException("发送端异常!");
}
}
}
/*接受端
*/
class Rece implements Runnable{
private DatagramSocket ds;
public Rece(DatagramSocket ds) {
this.ds=ds;
}
@Override
public void run() {
try {
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
while(true){
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String data=new String(dp.getData(),0,dp.getLength(),"BGK");
System.out.println(ip+data);
if("over".equals(data)||"886".equals(data))
break;
}
} catch (Exception e) {
throw new RuntimeException("接受端异常!");
}
}
} |
|