package cn.xlc.net.udp.mytest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class ChatTest {
public static void main(String[] args) throws SocketException {
/*
* 通过UDP协议完成聊天程序 一个负责发送数据的任务,一个负责接收 同时进行 多线程技术
*/
// 创建socket服务
// 发送端
DatagramSocket send = new DatagramSocket(8888);
DatagramSocket rece = new DatagramSocket(10000);
new Thread(new Send(send)).start();
new Thread(new Rece(rece)).start();
}
}
// 负责发送任务,通过UDPsocket发送
class Send implements Runnable {
// 任务对象一建立,需要socket对象
private DatagramSocket ds;
public Send(DatagramSocket ds) {
super();
this.ds = ds;
}
public void run() {
// 具体发送数据的内容
// 1.要发送的数据来自哪里?键盘录入
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
// 1.1读入数据
String line = null;
try {
while ((line = bufr.readLine()) != null) {
// 1.2将数据变成字节输入,封装到数据包中
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 10000);
// 3.将数据发送
ds.send(dp);
if ("over".equals(line)) {
break;
}
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
// 2.数据封装到数据包中。
// 3.将数据包发送出去。
}
}
class Rece implements Runnable {
private DatagramSocket ds;
public Rece(DatagramSocket ds) {
super();
this.ds = ds;
}
public void run() {
while (true) {
// 接收的具体内容
// 1.因为接收到数据存储到数据包中 数据包中必须有字节数组
byte[] buf = new byte[1024];
// 2.创建数据包对象
DatagramPacket dp = new DatagramPacket(buf, buf.length);
// 3.将受到的数据存储到数据包中
try {
ds.receive(dp);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
// 4.获取数据
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(), 0, dp.getLength());
System.out.println(ip + " :" + data);
if (data.equals("over")) {
System.out.println(ip + "....离开聊天室");
}
}
}
}
UDP通讯实例
最新推荐文章于 2024-07-11 14:50:23 发布