Java realizes chat function based on thread and TCP

This article implements the chat room of the beggar version. The main technologies used are thread and TCP, and there are three types: server server, server thread worker, and client client. Not much to say, just look at the code.
Server.java

import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.io.*;


public class Server {
	//创建了一个线程安全的键值对儿集合
	public static Map<String, Worker> threadMap = new ConcurrentHashMap<String, Worker>();
	
	public static void main(String[] args) {
		try {
			//在22222端口上运行服务
			ServerSocket ss = new ServerSocket(22222);
			System.out.println("服务器启动...");
			while(true) {
				Socket s = ss.accept();		
				//启动线程	
				new Thread(new Worker(s)).start();
				System.out.println("连接到一个用户" );
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
	}

}

Worker.java

import java.io.*;
import java.net.*;


 class Worker implements Runnable{
	 Socket s;
	 InputStream ips;
	 OutputStream ops;
	 BufferedReader br;
	 DataOutputStream dos;
	 
	 public Worker(Socket s) {
			this.s = s;
		}
	 
	@Override
	public void run() {
		try {
			ips = s.getInputStream();
			ops = s.getOutputStream();
			//输入流
			br = new BufferedReader(new InputStreamReader(ips));
			//输出流
			dos = new DataOutputStream(ops);
			while (true) {
				String strWord = br.readLine();
				//获取用户名
				String name = strWord.split(":")[0];
				//讲客户端添加到threadmap
				Server.threadMap.put(name, this);
				
				System.out.println(strWord +"---" + (strWord.length()-name.length()-1));			
				//quit正常关闭
				if (strWord.equalsIgnoreCase("quit"))
					break;
				//遍历map集合,给不是自己的线程发送消息
				for(Worker w : Server.threadMap.values()) {
					if(w != this){
						w.dos.writeBytes(strWord + System.getProperty("line.separator"));
					}			
				}
			}
			br.close();
			// 关闭包装类,会自动关闭包装类中所包装的底层类。所以不用调用ips.close()
			dos.close();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
}

Client.java

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {
	public static void main(String[] args) {
		try {
			//换成自己的ip地址,只在本地测试可以直接getHostAddress()
			Socket s = new Socket(InetAddress.getByName("192.168.56.1"), 22222);
			//打开输入输出流
			InputStream ips = s.getInputStream();
			BufferedReader brNet = new BufferedReader(new InputStreamReader(ips));
			
			OutputStream ops = s.getOutputStream();
			DataOutputStream dos = new DataOutputStream(ops);
			
			BufferedReader brKey = new BufferedReader(new InputStreamReader(System.in));
			
			System.out.println("Input your name:");
			Scanner sc = new Scanner(System.in);
			String name = sc.nextLine();
			while(true) {
				String strWord = brKey.readLine();
				if(strWord.equalsIgnoreCase("quit")) {
					break;
				}
				else {
					//System.out.println("i sent:" + strWord);
					//后面这个System.getProperty("line.separator")是换行的意思
					dos.writeBytes(name +":" + strWord + System.getProperty("line.separator"));
					
					System.out.println(brNet.readLine());
				}
			}			
			dos.close();
			brNet.close();
			brKey.close();
			s.close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}

The operation effect will not be released. The code written is relatively simple, and students should be correct if there are errors.
When running, run the server first, and then run the client, otherwise an exception will occur. What needs to be emphasized here is the Server class

public static Map<String, Worker> threadMap = new ConcurrentHashMap<String, Worker>();

This ConcurrentHashMap is a thread-safe hasmap. Changing it to a normal one will cause unexpected errors, mainly because of the use of threads. Knowledge about threads, parallel serial, synchronous and asynchronous is still learning, and will be shared in the future.

Guess you like

Origin blog.csdn.net/qq_42893430/article/details/98075845
Recommended