服务器端代码
package com.nettest; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPserver { public static void main(String[] args) throws IOException { byte[] data=null; DatagramPacket packet = null; DatagramSocket socket =new DatagramSocket(8800); UDPThread thread=null; int count =1; while(true){ data=new byte[1024]; packet = new DatagramPacket(data, data.length); System.out.println("服务器端已启动,等待客户端连接"); socket.receive(packet); System.out.println("客户端连接"); System.out.println("客户端连接数量为:"+count); thread=new UDPThread(packet,socket,data); thread.start(); count++; } } }
客户端代码
package com.nettest; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class UDPClient { public static void main(String[] args) throws IOException { InetAddress add=InetAddress.getByName("localhost"); int port=8800; byte[] data="用户名:admin;密码:123".getBytes(); DatagramPacket packet=new DatagramPacket(data, data.length,add,port); DatagramSocket socket=new DatagramSocket(); socket.send(packet); byte[] data2=new byte[1024]; DatagramPacket packe2=new DatagramPacket(data2, data2.length); socket.receive(packe2); String s=new String(data2,0,packe2.getLength()); System.out.println(s); socket.close(); } }
线程代码
package com.nettest; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class UDPThread extends Thread { byte[] data=null; DatagramPacket packet = null; DatagramSocket socket = null; DatagramPacket packet2=null; byte[] data2=null; UDPThread(DatagramPacket packet,DatagramSocket socket,byte[] data){ this.packet=packet; this.socket=socket; this.data=data; } public synchronized void run(){ try { String s=new String(data,0,packet.getLength()); System.out.println("客户端说:"+s); InetAddress add=packet.getAddress(); System.out.println("客户端IP:"+add); data2="欢迎您".getBytes(); int port=packet.getPort(); packet2=new DatagramPacket(data2, data2.length,add,port); socket.send(packet2); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ //socket.close(); } } }
第一运行结果一直是这样:
“服务器端已启动,等待客户端连接”这一句出现了两次,客户端正常。
还有如果我在线程代码中的finally里设置关闭datapramsocket在运行的时候会报错,请问老师应该怎么解决?
你把UDPServer中的:DatagramSocket socket=new DatagramSocket(8800),改为DatagramSocket socket=null;然后在死循环中初始化socket=new DatagramSocket(8800);这是因为UDP是一种临时的协议,每次传输完数据close之后,都必须再次创建
使用UDP协议时,socket是通用的,所以不能再线程UDPThread中关闭,应该在服务器UDPserver代码中关闭
使用线程的话,服务器端要一直阻塞啊,socket怎么能关闭呢是吧?
没有闭关Socket