Java-项目-002-无界面聊天室(含连接、多线程、多客户、私聊、udp通信)

Java-项目-002-聊天室(含连接、多线程、多客户、私聊、udp通信)-2020-6-25


具体效果没展示

一、Communication.java

import java.net.*; //引入网络包,以实现套接字连接
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;

import java.io.*; //引入输入输出流包,以进行数据的读写

/**
 * @author cloud
 *   聊天实训
 *
 */
public class Communication {
	static Map<String, Socket> map = new HashMap<>();

	public static void main(String[] args) {
		// startServer(4321);       //简单连接
		// Server(4321);            //多线程
		// Servers(4321);           //多客户
		// PrivateServer(4321);     //私聊
		//UDPServer(4321, 1234);      //udp通信

	}

	/*
	 * 1.简单的服务端连接
	 */
	public static void startServer(int port) {
		ServerSocket server = null; // server 成员变量的作用是用来打开服务器的端口
		Socket socket = null; // socket 成员变量的作用是用来与客户端建立套接字连接
		BufferedReader cin = null; // cin 成员变量的作用是用来建立输入流
		PrintStream cout = null; // cout 成员变量的作用是用来建立输出流
		System.out.println("服务器启动......");
		try {
			// 打开服务器端口
			server = new ServerSocket(port);
			// 添加提示信息
			System.out.println("系统提示:聊天服务器系统开始启动...... \n");
		} catch (IOException e1) { // 捕捉打开端口时可能产生的异常
			System.out.println("服务器端口打开出错\n");
		}
		if (server != null) { // 如果端口打开成功
			try {
				// 等待客户连接
				socket = server.accept();
			} catch (IOException e2) { // 捕捉等待客户连接时可能产生的异常
				System.out.println("用户连接服务器出错\n");
			}
			try {
				/*
				 * ,连接成功,则创建输入设备为套接字的输入流 由于需要进行中文的信息的收发,因此需要将输入流转换
				 */
				cin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				// 创建输出流,输出设备为套接字的输出流
				cout = new PrintStream(socket.getOutputStream());
				// 从输入流读入客户端发送的信息
				String str = cin.readLine(); // 语句 1
				// 将读入的信息进行显示
				System.out.println("从客户端读入如下的信息:" + str + "\n"); // 语句 2
			} catch (IOException e3) { // 捕捉可能产生的输入输出异常
				System.out.println("输入输出异常\n");
			}
		}
	}

	/*
	 * 2.简单的客户端连接
	 */
	public static void startClient(String ip, int port) {
		Socket socket = null; // socket 成员变量的作用是用来与服务器端建立套接字连接
		BufferedReader cin = null; // cin 成员变量的作用是用来建立输入流
		PrintStream cout = null; // cout 成员变量的作用是用来建立输出流
		System.out.println("客户端启动......");
		try {
			// 尝试与服务器进行连接,建立套接字
			socket = new Socket(ip, port);
			System.out.println("系统提示:与聊天服务器系统开始连接...... \n");
		} catch (IOException e1) { // 捕捉套接字建立时可能产生的异常
			System.out.println("服务器端口打开出错\n");
		}
		if (socket != null) { // 套接字建立成功
			try {
				cin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				cout = new PrintStream(socket.getOutputStream());
				// 构建发送信息
				String str = "来自" + InetAddress.getLocalHost().toString() + "的连接信息";
				// 将信息发送到服务器
				cout.println(str);
				System.out.println("向服务器发送如下的信息:" + str + "\n");
			} catch (IOException e3) { // 捕捉可能产生的异常
				System.out.println("输入输出异常\n");
			}
		}

	}

	/*
	 * 3.多线程的服务类
	 */
	public static void Server(int port) {
		ServerSocket server = null; // server 成员变量的作用是用来打开服务器的端口
		Socket socket = null; // socket 成员变量的作用是用来与客户端建立套接字连接
		BufferedReader cin = null; // cin 成员变量的作用是用来建立输入流
		PrintStream cout = null; // cout 成员变量的作用是用来建立输出流
		System.out.println("服务器启动......");
		try {
			// 打开服务器端口
			server = new ServerSocket(4321);
			// 添加提示信息
			ConnectSocket csocket = new ConnectSocket(server);
			csocket.start();
			System.out.println("系统提示:聊天服务器系统开始启动...... \n");
		} catch (IOException e1) { // 捕捉打开端口时可能产生的异常
			System.out.println("服务器端口打开出错\n");
		}

	}

	/*
	 * 4.多线程的客户类
	 */
	public static void Client(String ip, int port) {
		ServerSocket server = null; // server 成员变量的作用是用来打开服务器的端口
		Socket socket = null; // socket 成员变量的作用是用来与客户端建立套接字连接
		BufferedReader cin = null; // cin 成员变量的作用是用来建立输入流
		PrintStream cout = null; // cout 成员变量的作用是用来建立输出流
		System.out.println("客户端启动......");
		try {

			socket = new Socket(ip, port);
			// 接收数据
			ClientThread clientthread = new ClientThread(socket);
			clientthread.start();
			// 发送数据
			cin = new BufferedReader(new InputStreamReader(System.in));
			cout = new PrintStream(socket.getOutputStream(), true);
			while (true) {
				try {
					String message = cin.readLine();
					if (!message.equals("end")) {
						String send = message;
						cout.println(send);
					} else {
						System.out.println("正在关闭聊天室");
						Thread.sleep(1000);
						System.out.println("已关闭聊天室");
						if (socket != null) {
							socket.close();
						}
						break;
					}
				} catch (Exception ex) {
					System.out.println("连接不上服务器");

				}
			}
			System.out.println("系统提示:聊天服务器系统开始启动...... \n");
		} catch (IOException e1) { // 捕捉打开端口时可能产生的异常
			e1.printStackTrace();
		}

	}

	/*
	 * 5.多客户的服务端
	 */
	public static void Servers(int port) {
		ServerSocket server = null;
		System.out.println("多客户的服务器启动......");
		HashSet<Socket> clients = new HashSet<Socket>();
		try {
			server = new ServerSocket(port);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (server != null) {
			/* 开始用户连接 */
			ServerConnectSocket connect;
			connect = new ServerConnectSocket(server);
			connect.start();

		}
	}

	/*
	 * 6.多客户的客户端
	 */
	public static void Clients(String ip, int port, String name) {
		try {
			Socket socket = new Socket(ip, port);
			System.out.println("系统提示:与聊天服务器系统开始连接......\n");
			if (socket != null) {
				System.out.println("系统提示:与服务器连接成功......\n");
				BufferedReader cin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				PrintStream cout = new PrintStream(socket.getOutputStream(), true);
				String str = "PEOPLE:" + name;
				cout.println(str);
				ClientsReadMessageThread readThread = new ClientsReadMessageThread(socket);
				readThread.start();
				ClientsSendMessageThread sendThread = new ClientsSendMessageThread(socket, name);
				sendThread.start();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("服务器端口打开出错\n");
		}

	}

	/*
	 * 7.私聊的服务端
	 */
	public static void PrivateServer(int port) {
		System.out.println("私聊服务器已启动");

		Socket client;
		ServerSocket ss;
		try {
			ss = new ServerSocket(port);
			try {
				while (true) {

					client = ss.accept();
					BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
					String newconnectId = br.readLine();
					String talkTo = br.readLine();
					System.out.println(newconnectId + "上线了" + client.getInetAddress());
					map.put(newconnectId, client);
					PrivateServerThread t = new PrivateServerThread(client);
					t.setUserId(newconnectId);
					t.settalkTo(talkTo);
					t.start();
					System.out.println("当前服务器的用户有:" + map.size() + "个");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	/*
	 * 8.私聊的客户端
	 */
	static Socket socket = null;
	static String Id = null;
	static String target = null;
	static BufferedReader cin = null;
	static PrintWriter cout = null;

	public static void PrivateClient(String ip, int port) {

		System.out.println("私聊客户端已启动");
		try {
			socket = new Socket(ip, port);
			cout = new PrintWriter(socket.getOutputStream(), true);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// receive

		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					cin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					while (true) {
						System.out.println(cin.readLine());
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		t.start();
		// send
		System.out.println(socket);
		Scanner sc = new Scanner(System.in);
		String line = null;
		System.out.println("输入用户名:");
		Id = sc.nextLine();
		cout.println(Id);
		System.out.println("输入聊天对象:");
		target = sc.nextLine();
		cout.println(target);
		while ((line = sc.nextLine()) != null) {
			if (line.equalsIgnoreCase("exit"))
				break;
			cout.println(line);
		}
		sc.close();

	}

	/*
	 * 9.udp的服务端
	 */
	public static void UDPServer(int Receiveport, int Sendport) {
		System.out.println("UDP服务器启动中......");
		DatagramSocket sendSocket = null;
		DatagramSocket receiveSocket = null;
		try {
			// 实例化两个套接字

			sendSocket = new DatagramSocket();
			receiveSocket = new DatagramSocket(Receiveport);
			// 实例化线程并启动,一个用于接收消息,一个用于发送消息
			new Thread(new ServerSendThread(sendSocket, Sendport)).start();
			new Thread(new ServerReceiveThread(receiveSocket)).start();

		} catch (SocketException e) {
			System.out.println("异常");
		}

	}

	/*
	 * 10.udp的客户端
	 */
	public static void UDPClient(String ip, int Receiveport, int Sendport) {
		System.out.println("UDP客户端启动中......");
		DatagramSocket sendSocket = null;
		DatagramSocket receiveSocket = null;
		try {
			// 实例化两个套接字
			sendSocket = new DatagramSocket();
			receiveSocket = new DatagramSocket(Receiveport);
			// 实例化线程并启动,一个用于接收消息,一个用于发送消息
			new Thread(new SendThread(sendSocket, ip, Sendport)).start();
			new Thread(new ReceiveThread(receiveSocket)).start();
		} catch (SocketException e) {
			System.out.println("异常");
			e.printStackTrace();
		}
	}

}

//简单服务端连接
class ConnectSocket extends Thread {
	private Socket socket;
	ServerSocket server = null;

	public ConnectSocket(ServerSocket server) throws IOException {
		this.server = server;

	}

	public void run() { // 将多用户连接过程在 run 方法中实现
		while (true) { // 多个客户连接循环
			try {
				socket = server.accept(); // 等待客户连接
			} catch (IOException e) {
				System.out.println("用户连接服务器出错\n");
			}
			if (socket != null) {
				// 创建收发信息线程对象
				ReadMessageThread readThread = new ReadMessageThread(socket);
				// 激活线程
				readThread.start();
				SendMessageThread sendThread = new SendMessageThread(socket);
				// 激活线程
				sendThread.start();

			}
		}
	}
}

//多线程服务端接受数据
class ReadMessageThread extends Thread {
	/*
	 * 覆盖 Thread 类的 run 方法,在该方法中,循环从端口读入信息, 直到读入“QUIT”,则关闭套接字
	 */
	BufferedReader cin; // 输入流成员变量
	PrintStream cout; // 输出流成员变量
	Socket socket; // 套接字成员变量

	ReadMessageThread(Socket socket) {
		this.socket = socket;
		try {
			cin = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			cout = new PrintStream(this.socket.getOutputStream());
		} catch (IOException e) {
			System.out.println("输入输出流建立异常\n");
		}
	}

	public void run() {
		String str = "";
		BufferedReader jcin = new BufferedReader(new InputStreamReader(System.in));
		String message;

		while (true) {

			try {
				str = cin.readLine(); // 读入信息
				// System.out.println(str);
			} catch (IOException e) {
				System.out.println("输入输出异常\n");
			}

			if (str.equals("QUIT")) { // 若为“QUIT”,则关闭套接字,跳出循环
				try {
					socket.close();
					System.out.println("用户连接已关闭\n");
				} catch (IOException e) {
					System.out.println("套接字关闭异常\n");
				}
				break;
			} else // 不是 QUIT 信息,则将读入的信息进行显示
				System.out.println("从客户端读入如下的信息:" + str + "\n");
			// String message = "服务端已收到";

		}
	}
}

//多线程服务端发送数据
class SendMessageThread extends Thread {

	BufferedReader cin; // 输入流成员变量
	PrintStream cout; // 输出流成员变量
	Socket socket; // 套接字成员变量

	SendMessageThread(Socket socket) {
		this.socket = socket;
		try {
			cin = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			cout = new PrintStream(this.socket.getOutputStream());
		} catch (IOException e) {
			System.out.println("输入输出流建立异常\n");
		}
	}

	public void run() {
		String str = "";
		BufferedReader jcin = new BufferedReader(new InputStreamReader(System.in));
		String message;

		while (true) {
			try {
				message = jcin.readLine();
				String send = message;
				cout.println(send);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
		}
	}
}

//多线程客户端接收数据
class ClientThread extends Thread {
	private Socket socket;
	private BufferedReader cin = null;

	public ClientThread(Socket s) throws IOException {
		this.socket = s;
		cin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		System.out.println("请输入");
	}

	public void run() {
		try {
			while (true) {
				if (socket != null) {
					String message = null;
					if ((message = cin.readLine()) != null) {
						// 输出从服务器发送过来的消息
						System.out.println("从服务器发送过来的消息:" + message);
					}
				} else {
					System.out.println("线程已关闭");
					break;
				}
			}
			if (socket != null) {
				socket.close();
			}
		} catch (Exception ex) {
			System.out.println("聊天结束");
		}
	}
}

//多客户的服务端连接
class ServerConnectSocket extends Thread {
	static ArrayList<Client> clients = new ArrayList<Client>();
	ServerSocket server;

	public ServerConnectSocket(ServerSocket server) {
		this.server = server;
	}

	Socket socket;

	public void run() {
		while (true) {
			while (true) {
				try {
					socket = server.accept();
				} catch (IOException e2) {

				}

				Client c = new Client(socket);
				clients.add(c);
				c.start();
				// 服务器发送到客户的信息字符串,“PEOPLE”表示是客户列表信息
				String people = "PEOPLE";
				for (int i = 0; i < clients.size(); i++) {
					// 获取每一个服务器—客户交互信息线程
					Client c1 = (Client) clients.get(i);
					// 将用户名称添加到发送信息字符串
					people += ":" + c1.name;
				}
				// 调用信息广播成员方法,将用户列表信息发送到所有客户端

				for (int i = 0; i < clients.size(); i++) {
					// 获取每一个服务器—客户交互信息线程
					Client c2 = (Client) clients.get(i);
					// 通过线程的发送方法将信息发送出去
					c2.send(people);
				}
			}
		}
	}
}

//多客户的服务端存储
class Client extends Thread {
	String name; // 用来存储客户的连接姓名
	BufferedReader dis; // 用于实现接受从客户端发送来的数据流
	PrintStream ps; // 用来实现向客户端发送信息的打印流
	Socket socket; // 用于建立套接字
	boolean isRun = true;// 控制 Client 线程运行状态
	// 采用异步方式更新主界面中的图形组件
	static ArrayList<Client> clients = new ArrayList<Client>();

	public Client(Socket s) { // Client 线程的构造器
		socket = s; // 将服务器-客户端建立连接所形成的套接字传递到该线程
		try {
			// 存储特定客户 socket 的输入流,接受客户发送到服务器端的信息
			dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// 存储特定客户的输出流,发送服务器信息给客户*/
			ps = new PrintStream(socket.getOutputStream());
			// 读取接收到的信息,该信息为客户登陆信息
			String info = dis.readLine();
			// 将信息用":"分离
			StringTokenizer stinfo = new StringTokenizer(info, ":");
			// 用 head 存储关键区分字
			String head = stinfo.nextToken();
			// 第二个数据段是客户的名称
			name = stinfo.nextToken();
			clients.add(this);

		} catch (IOException e) {

		}

	}

	// 实现向客户端发送信息的方法
	public void send(String msg) {
		ps.println(msg);
		ps.flush();
	}

	// 读取客户端发送过来的信息
	public void run() {

		while (isRun) {
			String line = null;
			try {
				/* 读取客户端发送的信息 */
				line = dis.readLine();
			} catch (IOException e) {
				// 如果出错,则要关闭连接,并更新客户列表信息

				return;
			}
			// 对读入的信息进行分离,以确定信息类型
			StringTokenizer st = new StringTokenizer(line, ":");
			String keyword = st.nextToken();// 关键字,判断消息类型
			if (keyword.equalsIgnoreCase("MSG")) {
				/*
				 * 将接收到的客户聊天信息,通过调用信息广播成员方法, 发送到所有客户端
				 */
				System.out.println(line);
				for (int i = 0; i < clients.size(); i++) {
					// 获取每一个服务器—客户交互信息线程
					Client c = (Client) clients.get(i);
					// 通过线程的发送方法将信息发送出去
					c.send(line);
				}
				// 如果关键字是 QUIT,则是客户端发送的退出信息
			} else if (keyword.equalsIgnoreCase("QUIT")) {
				// 发送同意断开信息到客户端
				send("QUIT");
				// 关闭连接,并更新客户列表信息
				// 结束当前线程
				isRun = false;
			}
		}
	}
}

//多客户的客户端接受线程
class ClientsReadMessageThread extends Thread {
	boolean isRun = true;
	Socket socket = null;

	public ClientsReadMessageThread(Socket socket) {
		this.socket = socket;

	}

	public void run() {
		String line = "";

		BufferedReader cin;
		try {
			cin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			while (isRun) {
				try {
					line = cin.readLine();// 从端口读入一条信息
				} catch (IOException e) {
					System.out.println("输入输出异常\n");
				}
				StringTokenizer st = new StringTokenizer(line, ":");
				String keyword = st.nextToken();// 存储关键字,判断消息类型
				if (keyword.equalsIgnoreCase("QUIT")) {
					try {
						socket.close();
						System.out.println("接收到服务器同意断开信息,套接字关闭\n");

					} catch (IOException e) {
						System.out.println("套接字关闭异常\n");
					}
					isRun = false;
				} else if (keyword.equalsIgnoreCase("PEOPLE")) {
					ArrayList<String> imessage = new ArrayList<String>();
					while (st.hasMoreTokens())
						imessage.add(st.nextToken());
					System.out.println(imessage);
				} else {
					// 接收的是来自服务器的广播信息
					// 将信息的余下内容全部提取,并去掉首字符(冒号),并显示
					String message = st.nextToken("\0");
					message = message.substring(1);
					System.out.println(message + "\n");
				}
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}
}

//多客户客户端发送数据
class ClientsSendMessageThread extends Thread {

	BufferedReader cin; // 输入流成员变量
	PrintStream cout; // 输出流成员变量
	Socket socket; // 套接字成员变量
	String name;

	ClientsSendMessageThread(Socket socket, String name) {
		this.socket = socket;
		this.name = name;
		try {
			cin = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
			cout = new PrintStream(this.socket.getOutputStream());
		} catch (IOException e) {
			System.out.println("输入输出流建立异常\n");
		}
	}

	public void run() {
		String str = "";
		BufferedReader jcin = new BufferedReader(new InputStreamReader(System.in));
		String message;

		while (true) {
			try {
				message = jcin.readLine();
				String send = message;
				send = "MSG:" + name + ":" + send;
				cout.println(send);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
		}
	}
}

//私聊服务类
class PrivateServerThread extends Thread {
	String Id;
	Socket client = null;
	String message;

	public PrivateServerThread(Socket s) {
		this.client = s;
	}

	public void setUserId(String name) {
		this.Id = name;
	}

	public void settalkTo(String message) {
		this.message = message;
	}

	@Override
	public void run() {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = client.getInputStream();
			os = client.getOutputStream();
			BufferedReader cin = new BufferedReader(new InputStreamReader(is));
			PrintWriter cout = null;
			while (true) {
				String line = cin.readLine();
				cout = new PrintWriter(os, true);
				cout.println(this.Id + ": " + line);// 发给本用户
				System.out.println("转送中");
				Socket s = Communication.map.get(message);// 发给目标用户
				cout = new PrintWriter(s.getOutputStream(), true);
				cout.println(this.Id + ": " + line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

/*
 * UDP服务端_发送消息的线程类
 */
class ServerSendThread implements Runnable {
	// 将消息发送到指定端口和地址
	private int port;
	private String ip;
	private DatagramSocket sendSocket;

	public ServerSendThread(DatagramSocket sendSocket, int port) {
		this.sendSocket = sendSocket;
		this.port = port;
	}

	@Override
	public void run() {
		BufferedReader br = null;
		try {
			while (true) {
				// 键盘录入
				br = new BufferedReader(new InputStreamReader(System.in));
				String line = null;
				while ((line = br.readLine()) != null) {
					// 将键盘录入的内容转换成字节数组
					byte[] buf = line.getBytes();
					// 实例化一个数据包,指定发送的内容,内容长度,发送的地址和端口
					DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), port);
					// 发送数据包
					sendSocket.send(dp);
					// 打印发送的内容
					System.out.println("服务端发出::" + line);
				}
			}
		} catch (IOException e) {
			System.out.println("发送失败");
		} finally {
			if (sendSocket != null) {
				sendSocket.close();
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

/*
 * UDP服务端_接收消息的线程类
 */
class ServerReceiveThread implements Runnable {
	private DatagramSocket receiveSocket;

	public ServerReceiveThread(DatagramSocket receiveSocket) {
		this.receiveSocket = receiveSocket;
	}

	@Override
	public void run() {
		try {
			while (true) {
				// 一次接收的内容的最大容量
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				// 接收数据包
				receiveSocket.receive(dp);
				String data = new String(dp.getData(), 0, dp.getLength());
				// 取得数据包里的内容
				System.out.println("从客户端接受的信息:" + data);
			}
		} catch (IOException e) {
			System.out.println("接受失败");
		} finally {
			if (receiveSocket != null) {
				receiveSocket.close();
			}
		}
	}
}

/*
 * udp客户端_发送消息的线程类
 */
class SendThread implements Runnable {
	// 将消息发送到指定端口和地址
	private int port;
	private String ip;
	private DatagramSocket sendSocket;

	public SendThread(DatagramSocket sendSocket, String ip, int port) {
		this.sendSocket = sendSocket;
		this.ip = ip;
		this.port = port;
	}

	@Override
	public void run() {
		BufferedReader cin = null;
		try {
			while (true) {
				// 键盘录入
				cin = new BufferedReader(new InputStreamReader(System.in));
				String line = null;
				while ((line = cin.readLine()) != null) {
					// 将键盘录入的内容转换成字节数组
					byte[] buf = line.getBytes();
					// 实例化一个数据包,指定发送的内容,内容长度,发送的地址和端口
					DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(ip), port);
					// 发送数据包
					sendSocket.send(dp);
					// 打印发送的内容
					System.out.println("我发送:" + line);
				}
			}
		} catch (IOException e) {
			System.out.println("发送失败");
		} finally {
			if (sendSocket != null) {
				sendSocket.close();
			}
			if (cin != null) {
				try {
					cin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

/*
 * udp客户端接收消息的线程类
 */
class ReceiveThread implements Runnable {
	private DatagramSocket receiveSocket;

	public ReceiveThread(DatagramSocket receiveSocket) {
		this.receiveSocket = receiveSocket;
	}

	@Override
	public void run() {
		try {
			while (true) {
				// 一次接收的内容的最大容量
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				// 接收数据包
				receiveSocket.receive(dp);
				// 取得数据包里的内容
				String data = new String(dp.getData(), 0, dp.getLength());
				// 打印接收到的数据
				System.out.println("从服务端接受的信息:" + data);
			}
		} catch (IOException e) {
			System.out.println("接受失败");
		} finally {
			if (receiveSocket != null) {
				receiveSocket.close();
			}
		}
	}
}

二、Atest.java


public class Atest {
	public static void main(String[] args) {
		// Communication.startServer(4321);
		// Communication.Server(4321);
		// Communication.Servers(4321);
		// Communication.PrivateServer(4321);
		// Communication.UDPServer(4321,1234);

		// Communication.startClient("127.0.0.1", 4321);
		// Communication.Client("127.0.0.1", 4321);
		// Communication.Clients("127.0.0.1", 4321,"name1");
		// Communication.PrivateClient("127.0.0.1", 4321);
		// Communication.UDPClient("127.0.0.1",1234,4321);
	}
}

三、Btest.java


public class Btest {
	public static void main(String[] args) {
		// Communication.startClient("127.0.0.1", 4321);
		// Communication.Client("127.0.0.1", 4321);
		// Communication.Clients("127.0.0.1",4321,"name2");
		// Communication.PrivateClient("127.0.0.1", 4321);
		// Communication.UDPClient("127.0.0.1",1234,4321);
	}
}

四、Ctest.java


public class Ctest {
	public static void main(String[] args) {
		// Communication.startClient("127.0.0.1", 4321);
		// Communication.Client("127.0.0.1", 4321);
		// Communication.Clients("127.0.0.1",4321,"name3");
		// Communication.PrivateClient("127.0.0.1", 4321);
		// Communication.UDPClient("127.0.0.1",1234,4321);
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章