Java Socket 2

《Java TCP/IP Socket 编程》chapter2

这次使用的是UDP协议。

客户端发送一个字符串,服务器接受后,原封不动的返回,在客户端打印出来

Client:

import java.net.DatagramSocket; import java.net.DatagramPacket; import java.net.InetAddress; import java.io.IOException; import java.io.InterruptedIOException; public class UDPEchoClientTimeout { private static final int TIMEOUT = 3000; // Resend timeout (milliseconds) private static final int MAXTRIES = 5; // Maximum retransmissions public static void main(String[] args) throws IOException { if ((args.length < 2) || (args.length > 3)) { // Test for correct # of // args throw new IllegalArgumentException( "Parameter(s): []"); } InetAddress serverAddress = InetAddress.getByName(args[0]); // Server // address // Convert the argument String to bytes using the default encoding byte[] bytesToSend = args[1].getBytes(); int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7; DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(TIMEOUT); // Maximum receive blocking time // (milliseconds) DatagramPacket sendPacket = new DatagramPacket(bytesToSend, // Sending // packet bytesToSend.length, serverAddress, servPort); DatagramPacket receivePacket = // Receiving packet new DatagramPacket(new byte[bytesToSend.length], bytesToSend.length); int tries = 0; // Packets may be lost, so we have to keep trying boolean receivedResponse = false; do { socket.send(sendPacket); // Send the echo string try { socket.receive(receivePacket); // Attempt echo reply reception if (!receivePacket.getAddress().equals(serverAddress)) {// Check // source throw new IOException( "Received packet from an unknown source"); } receivedResponse = true; } catch (InterruptedIOException e) { // We did not get anything tries += 1; System.out.println("Timed out, " + (MAXTRIES - tries) + " more tries..."); } } while ((!receivedResponse) && (tries < MAXTRIES)); if (receivedResponse) { System.out.println("Received: " + new String(receivePacket.getData())); } else { System.out.println("No response -- giving up."); } socket.close(); } }

Server:

import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPEchoServer { private static final int ECHOMAX = 255; // Maximum size of echo datagram public static void main(String[] args) throws IOException { if (args.length != 1) { // Test for correct argument list throw new IllegalArgumentException("Parameter(s): "); } int servPort = Integer.parseInt(args[0]); DatagramSocket socket = new DatagramSocket(servPort); DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX); while (true) { // Run forever, receiving and echoing datagrams socket.receive(packet); // Receive packet from client System.out.println("Handling client at " + packet.getAddress().getHostAddress() + " on port " + packet.getPort()); socket.send(packet); // Send the same packet back to client packet.setLength(ECHOMAX); // Reset length to avoid shrinking buffer } /* NOT REACHED */ } }

你可能感兴趣的:(Java,J2EE)