关于udp使用多线程实现多客户端请问人写出来吗?按照之前的tcp那种写法不成功啊
如题,因为packet传到线程里后不起作用啊,测了下,不为空,但它的方法都用不了啊,有谁知道吗。老师没讲这个网上查到的资料也很有显。幕课之前也有人问同样的问题,但并没有回答
如题,因为packet传到线程里后不起作用啊,测了下,不为空,但它的方法都用不了啊,有谁知道吗。老师没讲这个网上查到的资料也很有显。幕课之前也有人问同样的问题,但并没有回答
2016-04-11
public class UDPServerThread extends Thread { DatagramSocket socket = null; DatagramPacket packet = null; public UDPServerThread(DatagramPacket packet,DatagramSocket socket){ this.packet = packet; this.socket = socket; } public void run(){ byte[] data = packet.getData(); String info = new String(data,0,packet.getLength()); System.out.println("我是服务器,客户端说:"+info); //响应客户端 InetAddress address = packet.getAddress(); int port = packet.getPort(); byte[] data2 = "欢迎您!".getBytes(); DatagramPacket packet2 = new DatagramPacket(data2, data2.length,address, port); try { socket.send(packet2); } catch (IOException e) { e.printStackTrace(); } } } /* * 服务器端,实现基于UDP的用户登陆 */ public class UDPServer { public static void main(String[] args) throws IOException { //创建服务器端DatagramSocket,指定端口号 DatagramSocket socket = new DatagramSocket(8800); byte[] data = new byte[1024];//创建字节数组,指定接收的数据报的大小 int count=0; System.out.println("*******服务器端已经启动,等待客户端发送数据**********"); while(true){ DatagramPacket packet = new DatagramPacket(data, data.length); socket.receive(packet); UDPServerThread serverThread = new UDPServerThread(packet, socket); serverThread.start(); count++; System.out.println("客户端的数量是"+count); } } }
仅供参考:
public class UdpSocketMilServerDemo {
public static void main(String[] args) {
DatagramSocket socket = null;
try {
/*
* 接受客户端发送到服务器的数据信息
*/
int count = 0;
//创建DatagramSocket,指定端口
socket = new DatagramSocket(8800);
while(true){
//创建DatagramPacket,用于存储客户端发送的信息
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
//接受从客户端发送来的请求信息,并存储在DatagramPacket中
socket.receive(packet);
UdpThread thread = new UdpThread(socket, data, packet);
thread.start();
count++;
System.out.println("总共有"+count+"个用户登录");
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
socket.close();
}
}
}
public class UdpThread extends Thread {
private DatagramSocket socket;
private byte[] data;
private DatagramPacket packet;
public UdpThread(DatagramSocket socket,byte[] data,DatagramPacket packet){
this.socket = socket;
this.data = data;
this.packet = packet;
}
@Override
public void run() {
try {
//读取获取到的客户信息
String info = new String(data, 0, packet.getLength());
System.out.println("我是服务端,客户端说:"+info);
/*
* 对客户端的请求进行响应
*/
//获取客户端主机信息和定义要响应的信息
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] data2 = "欢迎您!".getBytes();
//定义一个DatagramPaket,用户存放响应信息
DatagramPacket responsePacket = new DatagramPacket(data2, data2.length, address, port);
//发送响应信息
socket.send(responsePacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
举报