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);
	}
}

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