多线程式:
在实际使用过程中我们都会希望服务端能同时为多个客户端提供服务
最直接的办法就是每个客户端一个线程
这种方式会在一定意义上占用更多系统资源
package com.lei.socket.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiThreadServer {
//启动服务端监听
public void start(){
try{
ServerSocket server = new ServerSocket(port);
Socket client = null;
while(runFlag){
client = server.accept();
System.out.println("accept client " + client.getInetAddress().getHostAddress());
new Thread(new ClientHandle(client)).start();
}
server.close();
}catch(IOException e){
System.out.println("start error");
}
}
public static void main(String[] args){
MultiThreadServer s = new MultiThreadServer();
s.start();
}
class ClientHandle implements Runnable{
public ClientHandle(Socket s){
this.client = s;
}
//处理客户端请求
public void handleClient(){
try{
BufferedReader inReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter outWriter = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
while(true){
outWriter.write("please input String->");
outWriter.flush();
String str = inReader.readLine();
if(str.equalsIgnoreCase("quit")){
outWriter.write("quit ok");
client.close();
break;
}
else{
outWriter.write("reulst is :" + new StringBuffer(str).reverse().toString());
outWriter.write("\r\n");
}
}
}catch(IOException e){
System.out.println("Handle client error");
}
}
public void run(){
handleClient();
}
private Socket client;
}
private int port = 3000;
private boolean runFlag = true;
}