public class ServerThread extends Thread {
DatagramSocket socket = null;
public ServerThread(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
byte[] data = new byte[1024];// 创建字节数组,指定接收的数据包的大小
DatagramPacket packet = new DatagramPacket(data, data.length);
// 3接收客户端发送的数据
socket.receive(packet);
// 此方法在接收到数据包之前会一直阻塞
// 4.读取数据
String info = new String(data, 0, packet.getLength());
System.out.println("我是服务器,客户端说:" + info);
/*
* 向服务器端相应
*/
// 1.定义客户端的地址,端口号,数据
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] data2 = "欢迎你".getBytes();
// 2创建数据报包含相应信息
DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port);
// 3.响应客户端
socket.send(packet2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class UDPserver {
public static void main(String[] args) throws IOException, InterruptedException {
//1.创建服务器端dategramsocket,指定端口
DatagramSocket socket = new DatagramSocket(8800);
//2.创建数据报,用于接收客户端发送的数据
System.out.println("*********服务器已启动等待客户端发送数据*********");
int count = 0;
while(true){
ServerThread thread = new ServerThread(socket);
thread.sleep(1000);
thread.start();
count++;
System.out.println("客户端第"+count+"次连接服务器端");
}
}
}
public class UDPclient {
public static void main(String[] args) throws IOException {
//向服务器端发送数据
//1.定义服务器的地址,端口号,数据
InetAddress address = InetAddress.getByName("localhost");
int port = 8800;
byte [] data = "用户名 :admir ;密码:123;".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
//接收响应信息
//1.创建数据报,用于接收服务器端响应信息
byte [] data2 = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(data2, data.length);
socket.receive(packet2);
//3.读取数据
String reply = new String(data2,0,packet2.getLength());
System.out.println("我是客户端,服务器端说:"+reply);
}
}
打开App,阅读手记