基于UDP的服务器实现多线程时,第一个客户运行端不能在服务器登陆得到响应,第二个实行客户端,第一次执行已停止的客户端才能接受服务器的响应,服务器也才会得到第一个客户端的信息
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 UDPCilent { public static void main(String[] args) { try { /* * 向服务器端发送信息 */ //定义服务器ip,端口,信息 InetAddress address=InetAddress.getByName("localhost"); int port=8000; byte []data="用户名:kuerban;密码:668858".getBytes(); //建立DatagramPacket DatagramPacket packet=new DatagramPacket(data, 0, data.length, address, port); //建立DatagramSocket DatagramSocket socket=new DatagramSocket(); socket.send(packet); /* * 获取服务端发送信息 */ //建立数据包接受信息 byte bytes[]=new byte[1024]; DatagramPacket packet1=new DatagramPacket(bytes, bytes.length); socket.receive(packet1); String info=new String(bytes, 0, packet1.getLength()); System.out.println(info); socket.close(); } catch (UnknownHostException | SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /* * 服务器端,基于UDP实现用户登录 */ public class UDPServer { public static void main(String[] args) { try { /* * 接受信息 */ //建立一个DatagramSocket,指定端口 DatagramSocket socket=new DatagramSocket(8000); byte []bytes=new byte[1024]; //建立一个Datagrampacket,以接受数据 DatagramPacket packet=new DatagramPacket(bytes, bytes.length); /* * 发送数据 */ //启动服务器 System.out.println("服务器已启动"); while(true){ socket.receive(packet); //建立客户端ip,端口 InetAddress address=packet.getAddress(); int port=packet.getPort(); UDPthread thread=new UDPthread(socket,packet,address,port,bytes); thread.start(); } } catch (IOException e) { e.printStackTrace(); } } }
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPthread extends Thread{
DatagramPacket packet=null;
InetAddress address=null;
byte bytes[];
int port=0;
DatagramSocket socket=null;
public UDPthread(DatagramSocket socket,DatagramPacket packet,InetAddress address,int port,byte[] bytes) {
this.packet =packet;
this.address=address;
this.port=port;
this.socket=socket;
this.bytes=bytes;
}
public void run(){
//读取信息,输出信息
String info=new String(bytes, 0, packet.getLength());
System.out.println(info);
//建立信息,并发送
byte bytes1[]="登陆成功".getBytes();
DatagramPacket packet1=new DatagramPacket(bytes1, 0, bytes1.length,address,port);
//向客户端响应
try {
socket.send(packet1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}