1. 程式人生 > 實用技巧 >20.12.26 85. 最大矩形

20.12.26 85. 最大矩形

技術標籤:Java計算機網路基礎udpjava網路通訊

Java實現UDP通訊

環境

CentOS Linux release 8.1.1911 (Core)
java version "14.0.2" 2020-07-14

程式碼

伺服器端的Server程式需先於客戶端的Client程式執行

Client

其中,<host name>為伺服器端IP地址,<port>為伺服器程式監聽的埠號

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class UDPClient
{ private String hostName; private int port; private DatagramSocket datagramSocket; public UDPClient(String hostName, int port) { this.hostName = hostName; this.port = port; try { datagramSocket = new DatagramSocket(); } catch (SocketException
e) { e.printStackTrace(); } } public void sendMessage(String message) { byte[] buffer = message.getBytes(); try { DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(hostName), port); datagramSocket.
send(datagramPacket); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { final String HOST_NAME = "<host name>"; final int PORT = <port>; UDPClient udpClient = new UDPClient(HOST_NAME, PORT); String message = ""; while (!message.equals("exit")) { Scanner scanner = new Scanner(System.in); message = scanner.nextLine(); udpClient.sendMessage(message); } } }

Server

其中,<port>為程式監聽的埠號,需與客戶端設定的一致

import java.net.*;
import java.io.*;

public class UDPServer {
	private int port;
	private DatagramSocket datagramSocket;

	public UDPServer(int port) {
		this.port = port;
		try {
			datagramSocket = new DatagramSocket(port);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	public String receive() {
		byte[] buffer = new byte[1024];
		DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);

		try {
			datagramSocket.receive(datagramPacket);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String message = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
		return message;
	}

    public static void main(String[] args) throws Exception
	{
		String message = "";
		UDPServer udpServer = new UDPServer(<port>);
		while (!message.equals("exit")) {
			message = udpServer.receive();
			System.out.println(message);
		}
	}

}

雲伺服器安全組配置

安全組訪問規則入方向協議型別需設定為UDP

測試結果

Client

Hello
This is Client!
exit

Server

Hello
This is Client!
exit

最後

  • 由於博主水平有限,不免有疏漏之處,歡迎讀者隨時批評指正,以免造成不必要的誤解!