UDP一般用于安全性不高的点对点传输模式的程序,会存在两个终端,不存在服务器端。基本编程步骤如下:
1.创建数据Socket,指定端口号,java提供了java.net.DatagramSocket类支持,两端可以使用不同的端口号,比如:
DatagramSocket ds = new DatagramSocket(8888);
2.对于接收端,需提供一个byte数组进行数据的存储;对于发送消息端,还需要提供IP地址和端口号,如下:
//创建byte数组
byte[] buffer = new byte[1024];
//创建数据包对象
DatagramPacket datagramPacket = new DatagramPacket(buffer, 1024);
DatagramPacket dp = new DatagramPacket(str.getBytes(), 0, str.length(), InetAddress.getByName("localhost"), sendPort);
3.调用DatagramPacket的receive()或send()方法进行数据的接收和发送;
4.调用DatagramPacket的getData()方法得到byte数组的数据。
完整代码如下:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* Created by wjz on 2017/3/28.
*/
public class UDPChat {
public static void main(String[] args) throws Exception {
//参数:接收端口,发送端口,对方接收端口
new ReceiveThread(Integer.parseInt(args[0])).start();
new SendThread(Integer.parseInt(args[1]), Integer.parseInt(args[2])).start();
}
}
//接收消息线程
class ReceiveThread extends Thread {
private DatagramSocket ds;
public ReceiveThread(int port) {
super();
try {
this.ds = new DatagramSocket(port);
} catch (SocketException se) {
se.printStackTrace();
}
}
@Override
public void run() {
try {
//创建byte数组
byte[] buffer = new byte[1024];
//创建数据包对象
DatagramPacket datagramPacket = new DatagramPacket(buffer, 1024);
//循环
while (true) {
ds.receive(datagramPacket);
String str = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
System.out.println("接收到:" + str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ds.close();
}
}
}
//发送线程类
class SendThread extends Thread {
private DatagramSocket ds;
private int sendPort;
public SendThread(int port, int sendPort) {
super();
this.sendPort = sendPort;
try {
this.ds = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while ((str = br.readLine()) != null) {
DatagramPacket dp = new DatagramPacket(str.getBytes(), 0, str.length(), InetAddress.getByName("localhost"), sendPort);
ds.send(dp);
System.out.println("发送:" + str);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ds.close();
}
}
}