一个简单的UDP回显服务器
- 客户端给服务器发送一个字符串,服务器把这个字符串原封不动的返回(回显到服务器echo server) 相当于服务器开发当中的"hello world".
- 通过整个代码书写过程了解UDP的协议格式和发送数据的基本原理
- 服务端代码
package com.zb.network.test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpEchoServer {
public static void main(String[] args) throws IOException {
UdpEchoServer server = new UdpEchoServer(9090);
server.start();
}
private DatagramSocket socket = null;
public UdpEchoServer(int port) throws SocketException {
socket = new DatagramSocket(port);
}
public void start() throws IOException {
System.out.println("服务器启动");
while(true){
DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
socket.receive(requestPacket);
String request = new String(requestPacket.getData(),
0, requestPacket.getLength()).trim();
String response = process(request);
DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
response.getBytes().length, requestPacket.getSocketAddress());
socket.send(responsePacket);
System.out.printf("[%s:%d] req: %s; resp: %s\n", requestPacket.getAddress().toString(),
requestPacket.getPort(), request, response);
}
}
private String process(String request) {
return request;
}
}
package com.zb.network.test;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UdpEchoClient {
DatagramSocket socket = null;
String serverIp;
int serverPort;
public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
socket = new DatagramSocket();
this.serverIp = serverIp;
this.serverPort = serverPort;
}
public void start() throws IOException {
Scanner sc = new Scanner(System.in);
while (true){
System.out.print("-> ");
String request = sc.nextLine();
if (request.equals("exit")){
break;
}
DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
request.getBytes().length, InetAddress.getByName(serverIp), serverPort);
socket.send(requestPacket);
DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
socket.receive(responsePacket);
String response = new String(responsePacket.getData(), 0, responsePacket.getLength()).trim();
System.out.println(response);
}
}
public static void main(String[] args) throws IOException {
UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
client.start();
}
}
- 效果展示
- 日志分析
- 客户端端口号是由操作系统自动生成的,每次启动都有可能不一样
- 当晚我们还可以将我们的服务器部署到云服务器上,让别的小伙伴也能够访问到
- 部署方式也很简单,将我们写好的服务器代码打成jar包放在服务器跑即可,记得开放云服务器安全组对应的协议端口号,像这个就需要开放安全组的UDP协议的9090端口
|