TCP
服务端
@Log4j
public class TCPServer {
private boolean running = false;
public void start() {
running = true;
log.debug("TCP服务器已经启动,端口是 8888");
try (ServerSocket serverSocket = new ServerSocket(8888)) {
while (running) {
// 等待客户端请求,如果有请求就分配一个 Socket
Socket socket = serverSocket.accept();
// 输入
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String buffer;
while ((buffer = reader.readLine()) != null && !buffer.equals("")) {
log.info(buffer);
}
// 输出
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// 模拟 http 请求头
writer.write("HTTP/1.1 200 OK \r\n Content-type:text/html \r\n charset=UTF-8\r\n\r\n");
writer.write("<html><head><title>HTTP 请求</title></head><body><h1>HTTP 请求</h1></body></html>");
// 刷新输出流
writer.flush();
reader.close();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
running = false;
}
}
客户端
@Log4j
public class TCPClient {
public void start() {
String msg = "hello";
try (Socket socket = new Socket("127.0.0.1", 8888)) {
log.debug("TCP 客户端已经链接");
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.println(msg);
printWriter.flush();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP
发送端
@Log4j
public class UDPSend {
private boolean running = false;
public void start() {
running = true;
try (DatagramSocket datagramSocket = new DatagramSocket()){
log.debug("UDP 发送端已经启动");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while (running && (line = reader.readLine()) != null) {
byte[] bytes = line.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("127.0.0.1"), 10005);
datagramSocket.send(datagramPacket);
if (line.equals("bye")) {
stop();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
running = false;
}
}
接收端
@Log4j
public class UDPReceive {
private boolean running = false;
public void start() {
running = true;
try (DatagramSocket datagramSocket = new DatagramSocket(10005)) {
log.debug("UDP 接收端已经启动");
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
while (running) {
datagramSocket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
String msg = new String(data, 0, datagramPacket.getLength());
if (msg.equals("bye")) {
stop();
}
log.info(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop() {
running = false;
}
}