?本案例利用UPD与多线程实现简单的UDP报文发送
public class Send implements Runnable {
DatagramSocket datagramSocket = null;
BufferedReader reader;
private int port;
private String hostname;
private int ServerPort;
public Send(int port, String hostname, int serverPort) {
this.port = port;
this.hostname = hostname;
this.ServerPort = serverPort;
try {
datagramSocket = new DatagramSocket(port);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
System.out.println("发送端");
while (true) {
try {
String str = reader.readLine();
byte[] bytes = str.getBytes("UTF-8");
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, new InetSocketAddress(this.hostname, this.ServerPort));
datagramSocket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
?
package com.example.test1115.UDPTest;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Receive implements Runnable {
DatagramSocket datagramSocket = null;
private int port;
private String ClientName;
public Receive(int port, String hostname) {
this.port = port;
this.ClientName = hostname;
try {
datagramSocket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run(){
System.out.println("接受端");
while (true) {
try {
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
datagramSocket.receive(packet);
byte[] data = packet.getData();
String receive = new String(data, 0, data.length,"UTF-8");
System.out.println(this.ClientName + ":" + receive);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
?创建学生端和老师端,构造器里的数字是端口号,将其给成对方的即可
public class Teacher {
public static void main(String[] args) {
new Thread(new Receive(8086,"学生")).start();
new Thread(new Send(7777,"localhost",5555)).start();
}
}
public class Student {
public static void main(String[] args) {
new Thread(new Receive(5555,"老师")).start();
new Thread(new Send(6666,"localhost",8086)).start();//第一个是发送端的IP,第二个是对方的接受端IP
}
}
最终效果就是这样的
?
|