基于UDP的Socket多个客户端之间的简单通信

基于UDP的Socket多个客户端之间的简单通信

本案例包括一个UDPServer.java服务器端类,两个客户端UDPClient.java、UDPClient2.java类,两个线程类,分别为UDPServerRunnable.java和UDPClientThread
下面直接贴代码

服务器端类UDPServer.java

package com.UDP;

import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPService {
	public static void main(String[] args) {
		/*
		 * 接收客户端信息
		 */
		try {
			while(true) {
				DatagramSocket socket = new DatagramSocket(8888);
				UDPServerRunnable udpThread = new UDPServerRunnable(socket);
				udpThread.run();
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

服务器端调用线程类UDPServerRunnable.java

package com.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPServerRunnable implements Runnable {
	DatagramSocket socket = null;
	DatagramPacket packet = null;
	public UDPServerRunnable(DatagramSocket socket) {
		this.socket = socket;
	}
	@Override
	public void run() {
		try {
			//2、创建数据报
			byte[] data = new byte[1024];
			packet =  new DatagramPacket(data, data.length);
			System.out.println("我是服务器,等待客户端连接" );
			socket.receive(packet);//把数据保存到packet
			if (socket == null) {
				wait(5000);
			}
			String info = new String(data, 0, packet.getLength());
			String[] strings = info.split(" ");
			/*
			 * 对客户端进行响应
			 */
			//要发送的信息
			//定义客户端地址,端口
			byte[] fasong = strings[2].getBytes();
			InetAddress address = InetAddress.getByName(strings[0]);
			int port2 = Integer.parseInt(strings[1]);
			byte[] data2 = "你好,我是服务器,连接成功".getBytes();
			System.out.println("客户端端口:" + port2);
			DatagramPacket packet2 = new DatagramPacket(fasong, fasong.length, address, port2);
			socket.send(packet2);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if (socket != null) {
				socket.close();
			}
		}
	}
}

客户端线程类UDPClientThread.java

package com.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPClientThread extends Thread {
	DatagramSocket socket = null;
	public UDPClientThread(DatagramSocket socket) {
		this.socket = socket;
	}
	@Override
	public void run() {
		/*
		 * 接收服务器响应
		 */
		try {
			byte[] data2 = new byte[1024];
			DatagramPacket packet2 =  new DatagramPacket(data2, data2.length);
			socket.receive(packet2);
			String info = new String(data2, 0, packet2.getLength());
			System.out.println(info);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

客户端里面的代码基本相同,客户端的两个类中只有这两句不同

DatagramSocket socket = new DatagramSocket(8877);//客户端1
DatagramSocket socket = new DatagramSocket(8899);//客户端2

因为我是在同一台机器测试的,IP地址相同,为了区分不同的客户端,所以设置了两个不同的端口。如果读者把两个客户端运行在两台不同的机器,这两个端口可以相同(端口取值的一些知识,请自行查阅文档)

客户端1UDPClient.java

package com.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;
import java.util.Scanner;

public class UDPClient {
	public static void main(String[] args) {
		boolean isNot = true;
		try {
			/*
			 * 发送信息
			 */
			//1、定义服务器地址,端口,以及发送的信息
			DatagramSocket socket = new DatagramSocket(8877);
			System.out.println("用户名:8877");
			System.out.println("请输入对方IP、对方端口、和发送的内容,三者以空格分割(如:189.163.122.122 8801 你好)。按回车发送。");
			while(isNot) {
				UDPClientThread udpClientThread = new UDPClientThread(socket);
				udpClientThread.start();
				InetAddress address = InetAddress.getByName("111.111.111.111");//这里填写服务器端所在的IP地址
				int port = 8888;
				Scanner sc = new Scanner(System.in);
				String str = sc.nextLine();
				if (str.equals("t")) {
					isNot = false;
				}else {
					byte[] data = str.getBytes();
					//创建数据包
					DatagramPacket packet = new DatagramPacket(data, data.length,address,port);
					//创建DatagramSocket
					socket.send(packet);
				}
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

客户端2UDPClient2.java

package com.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;
import java.util.Scanner;

public class UDPClient2 {
	public static void main(String[] args) {
		boolean isNot = true;
		try {
			/*
			 * 发送信息
			 */
			//1、定义服务器地址,端口,以及发送的信息
			DatagramSocket socket = new DatagramSocket(8899);
			System.out.println("用户名:8899");
			System.out.println("请输入对方IP、对方端口、和发送的内容,三者以空格分割(如:189.163.122.122 8801 你好)。按回车发送。");
			while(isNot) {
				UDPClientThread udpClientThread = new UDPClientThread(socket);
				udpClientThread.start();
				InetAddress address = InetAddress.getByName("111.111.111.111");//这里填写服务器端所在的IP地址
				int port = 8888;
				Scanner sc = new Scanner(System.in);
				String str = sc.nextLine();
				if (str.equals("t")) {
					isNot = false;
				}else {
					byte[] data = str.getBytes();
					//创建数据包
					DatagramPacket packet = new DatagramPacket(data, data.length,address,port);
					//创建DatagramSocket
					socket.send(packet);
				}
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

运行时,必须先启动服务器类UDPServer.java 然后启动客户端类,发送信息是需要指定目标客户端的IP与端口号的
发送时文本格式:目标客户端IP、目标客户端端口、发送内容(如:192.168.111.111 8888 你好呀),回车发送。

运行结果

基于UDP的Socket多个客户端之间的简单通信_第1张图片
基于UDP的Socket多个客户端之间的简单通信_第2张图片

你可能感兴趣的:(java)