基于Socket的服務(wù)端多線(xiàn)程模式
public class HeavySocketClient {
private static ExecutorService tp =Executors.newCachedThreadPool();
private static final int sleep_time =1000 * 1000 * 1000 ;
public static class EchoClient implements Runnable{
@Override
public void run() {
Socket client =null ;
PrintWriter writer = null ;
BufferedReader reader = null ;
try {
client =new Socket ();
client.connect(new InetSocketAddress("localhost", 8000));
writer = new PrintWriter(client.getOutputStream() , true );
writer.print("H");
LockSupport.parkNanos(sleep_time);
writer.println("e");
LockSupport.parkNanos(sleep_time);
writer.println("e");
LockSupport.parkNanos(sleep_time);
writer.println("e");
LockSupport.parkNanos(sleep_time);
writer.println("e");
LockSupport.parkNanos(sleep_time);
writer.println("e");
LockSupport.parkNanos(sleep_time);
writer.println("e");
writer.flush();
reader =new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("from server : " +reader.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class MultiThreadEchoServer {
private static ExecutorService tp =Executors.newCachedThreadPool();
static class HandleMsg implements Runnable{
Socket clienSocket ;
public HandleMsg(Socket clienSocket) {
super();
this.clienSocket = clienSocket;
}
@Override
public void run() {
BufferedReader is = null ;
PrintWriter os = null ;
try {
is = new BufferedReader( new InputStreamReader(clienSocket.getInputStream()));
os =new PrintWriter(clienSocket.getOutputStream(),true);
String inputLine = null;
long b =System.currentTimeMillis() ;
while ((inputLine = is.readLine()) != null){
os.println(inputLine);
}
long e =System.currentTimeMillis() ;
System.out.println("spend:"+ (e - b) + "ms");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(is != null){
is.close();
}
if(os != null){
os.close();
}
clienSocket.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void main(String[] args) {
ServerSocket echoServer = null ;
Socket clientSocket = null ;
try {
echoServer =new ServerSocket(8000);
} catch (Exception e) {
System.out.println(e);
}
while(true){
try {
clientSocket = echoServer.accept() ;
System.out.println(clientSocket.getRemoteSocketAddress() + " connect !");
tp.execute(new HandleMsg(clientSocket));
} catch (Exception e) {
System.out.println(e);
}
}
}
}
- 客戶(hù)端與服務(wù)端的代碼實(shí)現(xiàn) 寺晌,在客戶(hù)端世吨,我們使用線(xiàn)程池實(shí)現(xiàn)10次請(qǐng)求,因?yàn)闀?huì)在輸出有個(gè)字符之后呻征。進(jìn)行1秒的等待耘婚。所以會(huì)延遲很長(zhǎng)時(shí)間。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者