发送端:
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.Reader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- /*
- * 发送端程序:用于发送信息
- */
- public class SendMessage implements Runnable {
- /*
- * 发送端成员变量: socket对象 目的地ip地址 通信端口号
- */
- private DatagramSocket socket;
- private InetAddress ip;
- private int port;
- public SendMessage(DatagramSocket socket, InetAddress ip, int port) {
- super();
- this.socket = socket;
- this.ip = ip;
- this.port = port;
- }
- @Override
- public void run() {
- // 缓冲输入流用于读取用户输入
- Reader in = new InputStreamReader(System.in);
- BufferedReader reader = new BufferedReader(in);
- while (true) {
- try {
- // 读取用户输入,并打包数据
- String line = reader.readLine();
- int length = line.getBytes().length;
- DatagramPacket dp = new DatagramPacket(line.getBytes(), length, ip, port);
- // 发送数据报包
- socket.send(dp);
- // 如果输入886,结束循环
- if("886".equals(line)){
- break;
- }
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 关闭资源
- try {
- reader.close();
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
复制代码
接收端:
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- /*
- * 接收端程序:用于接收信息
- */
- public class ReceiveMessage implements Runnable {
- /*
- * 接收端成员变量: 接收端socket对象
- */
- 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);
- } catch (IOException e) {
- e.printStackTrace();
- }
- String data = new String(dp.getData(), 0, dp.getLength());
- System.out.println(dp.getAddress().getHostName() + "-" + dp.getPort() + " : " + data);
-
- }
- }
- }
复制代码
客户端1:
- import java.io.IOException;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- public class Client1 {
- public static void main(String[] args) throws IOException {
- SendMessage sm = new SendMessage(new DatagramSocket(), InetAddress.getByName("kaven-PC"), 10010);
- ReceiveMessage rm = new ReceiveMessage(new DatagramSocket(10011));
-
- Thread t1 = new Thread(sm);
- Thread t2 = new Thread(rm);
-
- t1.start();
- t2.start();
- }
- }
复制代码
客户端2:
- import java.io.IOException;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- public class Client1 {
- public static void main(String[] args) throws IOException {
- SendMessage sm = new SendMessage(new DatagramSocket(), InetAddress.getByName("kaven-PC"), 10010);
- ReceiveMessage rm = new ReceiveMessage(new DatagramSocket(10011));
-
- Thread t1 = new Thread(sm);
- Thread t2 = new Thread(rm);
-
- t1.start();
- t2.start();
- }
- }
复制代码
|
|