一个通过UDP协议传输键盘输入数据的案例代码
发送端代码
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- public class SendMessage implements Runnable {
- private DatagramSocket socket;
- public SendMessage(DatagramSocket socket) {
- super();
- this.socket = socket;
- }
- @Override
- public void run() {
- // 不停获取用户的输入
- while (true) {
- BufferedReader br = new BufferedReader(new InputStreamReader(
- System.in));
- try {
- // 读取数据
- String message = br.readLine();
- // 打包数据
- DatagramPacket dp = new DatagramPacket(message.getBytes(),
- message.getBytes().length,
- InetAddress.getByName("kaven-PC"), 10086);
- // 发送数据
- socket.send(dp);
- // 判断是否结束发送
- if ("bye".equals(message)) {
- break;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- socket.close();
- }
- }
复制代码
接收端代码
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- public class ReceiveMessage implements Runnable {
- private DatagramSocket socket;
- public ReceiveMessage(DatagramSocket socket) {
- super();
- this.socket = socket;
- }
- @Override
- public void run() {
- // 循环接收数据
- while (true) {
- DatagramPacket dp = new DatagramPacket(new byte[1024], 0, 1024);
- try {
- socket.receive(dp);
- System.out.println(dp.getAddress().getHostName() + ":"
- + new String(dp.getData()));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
复制代码
测试类
- import java.io.IOException;
- import java.net.DatagramSocket;
- public class ChatDemo {
- public static void main(String[] args) throws IOException {
- //创建两个socket服务对象:一个用于发送数据,一个用于接收数据
- DatagramSocket sendSocket = new DatagramSocket();
- DatagramSocket receiveSocket = new DatagramSocket(10086);
- //创建发送端对象和接收端对象
- SendMessage send = new SendMessage(sendSocket);
- ReceiveMessage receive = new ReceiveMessage(receiveSocket);
- //创建两个线程用于发送和接收数据
- Thread sendThread = new Thread(send, "send");
- Thread receiveThread = new Thread(receive, "receive");
- //启动线程
- sendThread.start();
- receiveThread.start();
- }
- }
复制代码
|
|