主要用两个类 DatagramSocket DatagramPacket
连接步骤:
- 建立发送端,接收端。
- 建立数据包。
- 调用Socket的发送接收方法
- 关闭Socket。
发送端与接收端是两个独立的运行程序。
下面演示:
要求:UDP聊天程序
通过键盘录入获取要发送的信息。
将发送和接收分别封装到两个线程中
public class UDPChat {
public static void main(String[] args) {
try {
DatagramSocket send = new DatagramSocket(10001);
DatagramSocket receive = new DatagramSocket(10002);
new Thread(new Send(send) ).start();
new Thread(new Receive(receive)).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Send implements Runnable{
private DatagramSocket ds;
public Send(DatagramSocket send) {
this.ds = send;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while( (line=br.readLine())!=null ){
byte buf[] = line.getBytes();
//要用接收方的ip和接收端口
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.31.168"), 10004);
ds.send(dp);
if("over".equals(line)){
break;
}
}
ds.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
class Receive implements Runnable{
private DatagramSocket ds;
public Receive(DatagramSocket receive) {
this.ds = receive;
}
@Override
public void run() {
try {
byte buf[] = new byte[1024];//大小够存储一行就可以
while(true){
//接收数据
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
//解析数据
String ip = dp.getAddress().getHostAddress();
String info= new String(dp.getData(),0,dp.getLength());//只能用dp.getlength不能要byte的length
System.out.println(ip+"说:"+info);
if("over".equals(info)){
System.out.println(ip+"离开聊天室....");
//break;
}
}
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}