TCP编程——实现多人聊天室功能

通过上一篇方法就能够实现TCP简单连接,但是有个问题,不能实现多客户端连接,因为服务器端如果接到一个连接请求之后,就会进入代码对应的循环中。那么怎么实现多人聊天呢?

实际上可以使用多线程,这样就不会有上述问题了。只需要引入新线程来处理每个连接事务即可

package Net.TCP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPThreadServer {

	ServerSocket server;

	public static void main(String[] args) throws IOException {
		TCPThreadServer tcpserver=new TCPThreadServer();
		ServerSocket server=new ServerSocket(30002);
		while(true)
		{
			System.out.println("服务器等待中.......");
			final Socket socket=server.accept();
			Thread td=new Thread()
			{
				@Override
				public void run()
				{
					try {
						doClient(socket);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			};
			td.start();
			
		}
	}

	private static void doClient(Socket socket) throws IOException
	{
		System.out.println("接收到一个客户端信号"+socket.getInetAddress().getHostAddress()+"  名称是: "+socket.getInetAddress().getHostName());
		BufferedReader fromClient=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		BufferedReader message=new BufferedReader(new InputStreamReader(System.in));
		String line=fromClient.readLine();
		while(line!=null&&!line.equals("exit"))
		{
			System.out.println(socket.getInetAddress().getHostAddress()+":"+line);
			line=fromClient.readLine(); 
		}

		System.out.println(socket.getInetAddress().getHostAddress()+"退出");
		message.close();
		fromClient.close();
	}

}


 


这样一来又有个问题,会不断有客户端连接服务器端,怎么样控制数量呢?

比如我们聊天室就是10个人的聊天室,多了不行,那怎么办?

我们可以重写ServerSocket的accpet方法,并引入一个volatile变量进行标记,那样真的好吗?

最好是使用我们的线程池来管理吧,既然有线程池,就拿来主义吧,何必花心思自己弄呢。

package Net.TCP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPPoolServer {

	ServerSocket server;
	  // 构造一个线程池

    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS, new ArrayBlockingQueue(3),
            new ThreadPoolExecutor.DiscardOldestPolicy());
    
	public static void main(String[] args) throws IOException {
		TCPPoolServer tcpserver=new TCPPoolServer();
		ServerSocket server=new ServerSocket(30002);
		while(true)
		{
			System.out.println("服务器等待中.......");
			final Socket socket=server.accept();
			ClientJob job=new ClientJob(socket);
			tcpserver.threadPool.execute(job);
			
		}
	}

	static void doClient(Socket socket) throws IOException
	{
		System.out.println("接收到一个客户端信号"+socket.getInetAddress().getHostAddress()+"  名称是: "+socket.getInetAddress().getHostName());
		BufferedReader fromClient=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		BufferedReader message=new BufferedReader(new InputStreamReader(System.in));
		String line=fromClient.readLine();
		while(line!=null&&!line.equals("exit"))
		{
			System.out.println(socket.getInetAddress().getHostAddress()+":"+line);
			line=fromClient.readLine(); 
		}

		System.out.println(socket.getInetAddress().getHostAddress()+"退出");
		message.close();
		fromClient.close();
	}

}

class ClientJob implements Runnable
{
	
	Socket socket;
	public ClientJob(Socket socket)
	{
		this.socket=socket;
	}
	public void run() {
		try {
			TCPPoolServer.doClient(socket);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}


聊天结果如下:

服务器等待中.......
服务器等待中.......
接收到一个客户端信号192.168.100.156  名称是: PC
192.168.100.156:我叫***我来了
服务器等待中.......
接收到一个客户端信号192.168.100.241  名称是: 192.168.100.241
192.168.100.241:hi 我叫韩梅梅
192.168.100.241:今天天气不错啊
192.168.100.156:是啊 我出去完了 先退了
192.168.100.156退出
192.168.100.241:我也走了
192.168.100.241退出

 

 

 

你可能感兴趣的:(网络编程)