使用缓冲池方式,进行TCP通信

上海驾校

1、我贴出的主要是核心代码,有些类为自己定义,并未贴出,大家可以主要看实现思路

2、核心代码

public class Server {
	private ServerSocket serverSocket;
	private ExecutorService executorService;// 线程池
	private boolean isStarted = true;
	private Socket socket;

	public Server() {
		try {
			serverSocket = new ServerSocket(Constants.SERVER_PORT);
			executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
					.availableProcessors() * 50);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			quit();
		}
	}
	
	public void start(){
		System.out.println(MyDate.getDateCN());
		while(isStarted){
			try {
				socket = serverSocket.accept();
				String ip = socket.getInetAddress().toString();
				System.out.println(MyDate.getDateCN() + " 用户:" + ip + " 已建立连接");
				if(socket.isConnected()){
					executorService.execute(new SocketToask(socket));
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(socket != null){
			try { 
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(serverSocket != null){
			try {
				serverSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block 
				e.printStackTrace();
			}
		}
	}
	
	private final class SocketToask implements Runnable{
		
		private Socket socket;
		private InputThread in;
		private OutputThread out;
		private OutputThreadMap map;
		
		public SocketToask(Socket socket) {
			this.socket = socket;
		}
		
		@Override
		public void run() {
			out = new OutputThread(socket, map);//
			// 先实例化写消息线程,(把对应用户的写线程存入map缓存器中)
			in = new InputThread(socket, out, map);// 再实例化读消息线程
			out.setStart(true);
			in.setStart(true);
			in.start();
			out.start();
		}
		
	}
	
	public void quit() {
		try {
			this.isStarted = false;
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 

	public static void main(String[] args) {
		Server server = new Server();
		server.start();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值