首页 > 代码库 > java基础入门-建立能够多client链接的ServerSocket

java基础入门-建立能够多client链接的ServerSocket

承接上一篇文章,今天谈论一下能够多client链接的ServerSocket。

这里面注意涉及到的技术点是:

1.ServerSocket

2.多线程


这次我们分成两个类来实现,先上代码:

package com.test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class ThreadedEchoHandler implements Runnable {

	private Socket socket = null;

	public ThreadedEchoHandler(Socket s) {
		this.socket = s;
	}

	@Override
	public void run() {
		InputStream inputStream;
		try {
			inputStream = socket.getInputStream();
			OutputStream outputStream = socket.getOutputStream();
			Scanner scanner = new Scanner(inputStream);
			PrintWriter printWriter = new PrintWriter(outputStream, true);
			printWriter.println("welcome to testServer");
			boolean done = false;
			while (!done && scanner.hasNextLine()) {
				String line = scanner.nextLine();
				printWriter.println("Echo:" + line);
				if (line.trim().equals("bye")) {
					done = true;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
ThreadedEchoHandler类主要实现的功能跟上一篇几乎相同。都是接受client发过来的数据,然后复制一下打印出来,可是这里面继承了Runnable,能够支持多线程


package com.test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TestSocket {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(8189);
		while (true) {
			Socket socket = serverSocket.accept();
			ThreadedEchoHandler handler = new ThreadedEchoHandler(socket);
			Thread thread = new Thread(handler);
			thread.start();
		}
	}
}

TestSocket依旧是測试类,这里跟上一篇文章有差别的地方就在while循环里面,每一个client链接过来,他都会开启一个独立线程来服务

扩展一下,这里的測试类仅仅是用来測试用的,假设考虑到性能的问题,这里通常会採取线程池,并且还须要有检測链接是否还在的检測类,不然随着client链接的添加,内存直接爆掉。



并且这两个类还欠缺了一些东西,譬如client如何退出?检測链接?半关闭?等等,这些后面待续






java基础入门-建立能够多client链接的ServerSocket