循环无连接服务器设计
题目:设计一个循环,无连接的回射服务器。设计和代码
设计思路无非是,服务器创建数据报socket,监听端口就行了,echo服务默认是7号端口。监听后有数据发送就用byte[]接收转为字符串打印,没什么问题再转为byte[]发送回去
首先是服务器的设计:
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPServer{ public static void main(String[] args) throws Exception { //创建socket DatagramSocket socket = new DatagramSocket(7); System.out.println("服务器启动..."); while(true){ //创建接收缓存 byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, data.length); socket.receive(packet); String recive = new String(data, 0, packet.getLength()); InetAddress id=packet.getAddress(); System.out.println(id+"客户端发送:" + recive); //返回相同的内容 byte[] data_ret=recive.getBytes(); DatagramPacket packet_ret = new DatagramPacket(data_ret, data_ret.length, packet.getAddress(), packet.getPort()); String ret = new String(data_ret); socket.send(packet_ret); System.out.println("返回消息:"+ret); } } }
写完后,进行测试,如何测试?自己再写一个UDP发送工具
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class UDPClient { public static void main(String[] args) throws IOException { DatagramSocket dsocket = new DatagramSocket(); Scanner scan=new Scanner(System.in); String host = "127.0.0.1"; int port = 7; //简单的模拟UDP发送 while(true){ System.out.print("发送:"); String msg = scan.nextLine(); InetAddress address = InetAddress.getByName(host); DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(), address, port); dsocket.send(packet); } } }
启动服务器后:
不断用客户端发送消息:
服务器响应: