Пример 4.1. Типовое приложение клиент/сервер с использованием UDP сокетов. Давайте начнем вместе с сервера. Метод main() создает образец сервера и вызывает метод runServer(). Этот метод связывается с портом 8001 на локальной главной ЭВМ и ждет пакет. После того, как пакет приходит, он извлекает команду и посылает ответ обратно отправителю (клиенту). Если это была команда выхода, то сервер закрывает себя, а также закрывает сокет, на котором осуществлялось прослушивание. Обратите внимание, что при создании датаграмного пакета для посылки, мы также внедряем адрес адресата и порта. Клиент начинает работу, соединяясь с сервером на локальной главной ЭВМ на порте 8001, а затем посылает команду для выбора версии сервера. Затем используется класс java.net.InetAddress для определения адреса сервера. После этого он отображает полученный ответ. В заключение, осуществляется посылка команды для выключения сервера и закрытия сокета. //Листинг UDPServer.java import java.net.*; import java.io.*; /** The UDP server. */ public class UDPServer { /** The default port for the server. */ public final static int DEFAULT_PORT = 8001; /** The version command. */ public final String VERSION_CMD = "VERS"; /** The quit command. */ public final String QUIT_CMD = "QUIT"; /** The server version. */ public final byte[] VERSION = { 'V', '2', '.', '0' }; /** The unknown command. */ public final byte[] UNKNOWN_CMD = { 'U', 'n', 'k', 'n', 'o', 'w', 'n', ' ', 'c', 'o', 'm', 'm', 'a', 'n', 'd' }; /** Runs the server. */ public void runServer() throws IOException { DatagramSocket s = null; try { // The stop flag boolean stopFlag = false; // The buffer to hold a datagram packet byte[] buf = new byte[512]; // Create the socket and bind to a particular port s = new DatagramSocket(DEFAULT_PORT); System.out.println("UDPServer: Started on " + s.getLocalAddress() + ":" + s.getLocalPort()); while(!stopFlag) { // Receive a packet DatagramPacket recvPacket = new DatagramPacket(buf, buf.length); s.receive(recvPacket); // Extract the command from the packet String cmd = new String(recvPacket.getData()).trim(); System.out.println("UDPServer: Command: " + cmd); // The response packet DatagramPacket sendPacket = new DatagramPacket(buf, 0, recvPacket.getAddress(), recvPacket.getPort()); // The number of bytes in the response int n = 0; // Handle the command if (cmd.equals(VERSION_CMD)) { n = VERSION.length; System.arraycopy(VERSION, 0, buf, 0, n); } else if (cmd.equals(QUIT_CMD)) { // Stop the server stopFlag = true; continue; } else { n = UNKNOWN_CMD.length; System.arraycopy(UNKNOWN_CMD, 0, buf, 0, n); } // Update the response sendPacket.setData(buf); sendPacket.setLength(n); // Send the response s.send(sendPacket); } // while(server is not stopped) System.out.println("UDPServer: Stopped"); } finally { // Close if (s != null) { s.close(); } } } /** Main. */ public static void main(String[] args) { try { UDPServer udpSvr = new UDPServer(); udpSvr.runServer(); } catch(IOException ex) { ex.printStackTrace(); } } } //Листинг UDPClient.java import java.net.*; import java.io.*; /** The UDP client. */ public class UDPClient { /** Runs the client. */ public void runClient() throws IOException { DatagramSocket s = null; try { // The buffer byte[] buf = new byte[512]; // Create a socket on any available port s = new DatagramSocket(); System.out.println("UDPClient: Started"); // The version command byte[] verCmd = { 'V', 'E', 'R', 'S' }; // The data to transmit DatagramPacket sendPacket = new DatagramPacket(verCmd, verCmd.length, InetAddress.getByName("127.0.0.1"), 8001); s.send(sendPacket); // Fetch the server response DatagramPacket recvPacket = new DatagramPacket(buf, buf.length); s.receive(recvPacket); // Extract the server version String version = new String(recvPacket.getData()).trim(); System.out.println("UDPClient: Server Version: " + version); // The quit command byte[] quitCmd = { 'Q', 'U', 'I', 'T' }; // Shutdown the server sendPacket.setData(quitCmd); sendPacket.setLength(quitCmd.length); s.send(sendPacket); System.out.println("UDPClient: Ended"); } finally { // Close if (s != null) { s.close(); } } } /** Main. */ public static void main(String[] args) { try { UDPClient client = new UDPClient(); client.runClient(); } catch(IOException ex) { ex.printStackTrace(); } } } Вначале запустите сервер, затем клиент. Результаты работы приложений: Работа приложения сервера | Работа приложения клиента | UDPServer: Started on 0.0.0.0/0.0.0.0:8001 | UDPClient: Started | UDPServer: Command: VERS | UDPClient: Server Version: V2.0 | UDPServer: Command: QUIT | UDPClient: Ended | UDPServer: Stopped | Press any key to continue | Press any key to continue | | |