w ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = -1;
while ((len = socketIn.read(buff)) != -1) {
buffer.write(buff, 0, len);
}
System.out.println(new String(buffer.toByteArray()));
(4)当调用Socket的close()方法关闭Socket时,它的输入流和输出流都被关闭。如果仅仅希望关闭 输入或输出流其中之一,可调用半关闭方法:shutdownInput()和shutdownOutput()。先后调用Socket的 shutdownInput()和shutdownOutput()方法,仅仅关闭输入流和输出流,并不等价于调用close()方法。在 通信结束后仍然需要调用close()方法,因为该方法才会释放Socket占用的资源。
Java Socket构建阻塞的TCP通信(4)
时间:2011-07-22 “子 孑” 博客
4.多线程服务器
EchoServer只能顺序的处理Client端的请求,这里使用ExecutorService指定一个线程池用于处理连接 请求。
private ExecutorService executorService; // 线程池
private final int POOL_SIZE = 4; // 单个CPU时线程池中工作线程的数目
…….
executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
.availableProcessors()* POOL_SIZE);
……
try {
socket = serverSocket.accept();
executorService.execute(new Handler(socket));
} catch (IOException e) {
e.printStackTrace();
}
Hander类封装了原来处理连接请求的逻辑,只要当前线程池中有空闲的线程,就可以用于处理请求。
源代码MultiEchoServer.java
public class MultiEchoServer {
private int port = 8000;
private ServerSocket serverSocket;
private ExecutorService executorService; // 线程池
private final int POOL_SIZE = 4; // 单个CPU时线程池中工作线程的数目
public MultiEchoServer() throws IOException {
serverSocket = new ServerSocket(port);
executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
.availableProcessors()
* POOL_SIZE);
System.out.println("Server Start");
}
public void service() {
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
executorService.execute(new Handler(socket));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException {
new MultiEchoServer().service();
}
}
class Handler implements Runnable {
private Socket socket;
public Handler(Socket socket) {
this.socket = socket;
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut, true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn));
}
public String echo(String msg) {
return "echo:" + msg;
}
public void run() {
try {
System.out.println("New connection accepted "
+ socket.getInetAddres
|