首页 > 代码库 > Java网络编程(tcp在服务器上应用多线程)

Java网络编程(tcp在服务器上应用多线程)

package org.tcp;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;


public class EchoThread implements Runnable {
private Socket client = null;
public EchoThread(Socket client){
this.client = client;
}
@Override
public void run() {
// TODO 自动生成的方法存根
PrintStream out = null;
BufferedReader buf = null;
try{
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintStream(client.getOutputStream());
boolean flag = true;
while(flag){
String str = buf.readLine();
if(str == null||"".equals(str)){
flag = false;
}else{
if("bye".equals(str)){
flag = false;
}else{
out.println("ECHO:"+str);
}
}
}
out.close();
client.close();
}catch(Exception e){
}
}


}


package org.tcp;


import java.net.ServerSocket;
import java.net.Socket;


public class EchoThreadSocket {
public static void main(String[] args) throws Exception{
ServerSocket server = null;
Socket client = null;
server = new ServerSocket(8888);
boolean f = true;
while(f){
System.out.println("服务器运行,等待客户端链接。");
client = server.accept();
new Thread(new EchoThread(client)).start();
}
server.close();
}
}