UDP不需要实现两个用户连接就可以发送消息,所以直接开两个线程,一个发送,一个接受就可以实现。
Sever端程序: 一,调用DatagramSocket(int port)创建一个数据报套接字,绑定在指定端口上; 二,调用DatagramPacket(byte[] buf,int length),建立一个字节数组来接收UDP包; 三,调用DatagramSocket.receive(); 四,最后关闭数据报套接字。
Client端程序: 一,调用DatagramSocket()创建一个数据报套接字; 二,调用DatagramPacket(byte[] buf,int offset,InetAddress address,int port),建立要发送的UDP包 三,调用DatagramSocket类的send方法发送数据包; 四,关闭数据报套接字。
数据报套接字发送成功后,相当于建立了一个虚连接,双方可以发送数据。
接收端:
代码语言:javascript复制package net.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Receiver implements Runnable {
private int port;
private DatagramSocket datagramSocket;
public Receiver(int port) throws SocketException {
this.port = port;
datagramSocket = new DatagramSocket(port);
}
@Override
public void run() {
while (true) {
try {
byte[] buf = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
datagramSocket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
String strdata = new String(data, 0, data.length);
System.out.println(strdata);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
发送端:
代码语言:javascript复制package net.udp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Send implements Runnable {
BufferedReader reader = null;
private String adress;
private int port;
private DatagramSocket datagramSocket;
public Send(String adress, int port) throws SocketException {
this.adress = adress;
this.port = port;
datagramSocket = new DatagramSocket();
InputStream in;
reader = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
while (true) {
try {
byte[] buf = reader.readLine().getBytes();
DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, InetAddress.getByName(adress), port);
datagramSocket.send(datagramPacket);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
用户一
代码语言:javascript复制package net.udp;
import java.net.SocketException;
public class Test_1 {
public static void main(String[] args) throws SocketException {
Send send = new Send("127.0.0.1", 6666);
Receiver receiver = new Receiver(8080);
new Thread(send).start();
new Thread(receiver).start();
}
}
用户二
代码语言:javascript复制package net.udp;
import java.net.SocketException;
public class Test_2 {
public static void main(String[] args) throws SocketException {
Send send = new Send("127.0.0.1", 8080);
Receiver receiver = new Receiver(6666);
new Thread(send).start();
new Thread(receiver).start();
}
}