一.服务端代码:
import java.io.*; import java.net.*; public class UDPEchoServer { private static final int ECHOMAX = 255; // Maximum size of echo datagram public static void main(String[] args) throws IOException { int servPort = 5500; // Server port 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 */ } }
二.客户端代码:
import java.net.*; import java.io.*; 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 { InetAddress serverAddress = InetAddress.getByName("127.0.0.1"); // Server address int servPort = 5500; // Server port // Convert the argument String to bytes using the default encoding byte[] bytesToSend = "Hi, World".getBytes(); DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(TIMEOUT); // Maximum receive blocking time(milliseconds) // Sending packet DatagramPacket sendPacket = new DatagramPacket(bytesToSend, 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(); } }
上述代码的UDP服务端是单线程,一次只能服务一个客户端。
以上就是本文的全部内容,查看更多Java的语法,大家可以关注:《Thinking in Java 中文手册》、《JDK 1.7 参考手册官方英文版》、《JDK 1.6 API java 中文参考手册》、《JDK 1.5 API java 中文参考手册》,也希望大家多多支持。
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索java
, 客户端
, socket
, udp
, 服务端
单线程
qt udp socket编程、linux udp socket编程、socket udp编程、java udp socket编程、mfc udp socket编程,以便于您获取更多的相关知识。
时间: 2024-09-29 06:41:40