Java Socket实现基于TCP和UDP多线程通信(3)

  5. 发送方的DatagramPacket构造方法传递四个参数包含数据内容,数据大小,地址和端口号。接收方的DatagramPacket构造方法有两个参数接收数据和数据大小。

2.5 创建服务器线程处理类UDPThread

  注意,DatagramSocket的实例socket不能关闭,会出现SocketException。读取数据用到的new String(packet.getData(), 0, packet.getLength()),参数表示数据报中的字节数组,位置和长度。

package com.linuxidc; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPThread implements Runnable{ DatagramSocket socket = null; DatagramPacket packet = null; public UDPThread(DatagramSocket socket,DatagramPacket packet) { this.socket = socket; this.packet = packet; } @Override public void run() { String info = null; InetAddress address = null; int port = 8800; byte[] data2 = null; DatagramPacket packet2 = null; try { info = new String(packet.getData(), 0, packet.getLength()); System.out.println("我是服务器,客户端说:"+info); address = packet.getAddress(); port = packet.getPort(); data2 = "我在响应你!".getBytes(); packet2 = new DatagramPacket(data2, data2.length, address, port); socket.send(packet2); } catch (IOException e) { e.printStackTrace(); } //socket.close();不能关闭 } }

2.6 创建服务器端类

package com.linuxidc; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPServer { public static void main(String[] args) throws IOException { DatagramSocket socket = new DatagramSocket(8800); DatagramPacket packet = null; byte[] data = null; int count = 0; System.out.println("***服务器端启动,等待发送数据***"); while(true){ data = new byte[1024];//创建字节数组,指定接收的数据包的大小 packet = new DatagramPacket(data, data.length); socket.receive(packet);//此方法在接收到数据报之前会一直阻塞 Thread thread = new Thread(new UDPThread(socket, packet)); thread.start(); count++; System.out.println("服务器端被连接过的次数:"+count); InetAddress address = packet.getAddress(); System.out.println("当前客户端的IP为:"+address.getHostAddress()); } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/027107e4e256aeda447bcb62dc9884a3.html