客户端
import java.io.*;
import java.net.*;
public class UDPClientTest {
public static void main(String args[]) {
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket(3456);
String string = "0000009390832";
byte[] databyte = new byte[100];
databyte = string.getBytes();
DatagramPacket sendPacket = new DatagramPacket(databyte, string.length(),
InetAddress.getLocalHost(), 10000);
sendSocket.send(sendPacket);
System.out.println("客户端开始传送数据!");
} catch (SocketException e) {
System.out.println("不能打开数据报Socket,或数据报Socket无法与指定端口连接!");
} catch (IOException ioe) {
System.out.println(ioe.toString());
} finally {
sendSocket.close();
}
}
}
服务器(receive会阻塞,采用线程)
import java.io.*;
import java.net.*;
public class UDPServerTest {
static public void main(String args[]) {
try {
DatagramSocket receiveSocket = new DatagramSocket(10000);
byte buf[] = new byte[1000];
DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
System.out.println("开始接受数据:");
//启动接收端线程
new Thread(new recthread(receiveSocket,receivePacket)).start();
}
catch (SocketException e) {
e.printStackTrace();
System.exit(1);
}
}
}
//因为要一直接收数据,所以接收receive会阻塞,所以创建一个线程,防止阻塞
class recthread extends Thread{
DatagramSocket ds=null;
DatagramPacket dp;
public recthread(DatagramSocket ds,DatagramPacket dp){
this.ds=ds;
this.dp=dp;
}
public void run( ){
while (true) {
try {
ds.receive(dp);
} catch (IOException e) {
e.printStackTrace();
}
String name = dp.getAddress().toString();
System.out.println("\n来自主机:" + name + "\n端口:" + dp.getPort());
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println("接受到的数据是: " + s);
}
}
}