老师的作业第一次运行一直不正常,还有socket关闭的问题,请帮忙看下
服务器端代码
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在运行的时候会报错,请问老师应该怎么解决?