通过java中的socket技术编写能够回显客户端输入的多线程服务器端

2024-11-23 08:35:21
推荐回答(1个)
回答1:

import java.io.*;
import java.net.*;
public class EchoServer {
public static void main(String[] args) {
new EchoServer().startServer();
}
boolean bstop=false;
public void startServer() {
try {
//创建服务器,并开放88端口
ServerSocket server=new ServerSocket(88);
System.out.println("服务于88端口\n客户端发exit/quit结束当前连接;发stop停止服务器");
while(!bstop){
//监听服务器端口,一旦有数据发送过来,那么就将数据封装成socket对象
//如果没有数据发送过来,那么这时处于线程阻塞状态,不会向下继续执行
Socket socket=server.accept();
System.out.println("客户端信息:"+socket.getRemoteSocketAddress());
new EchoThread(socket).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}

class EchoThread extends Thread{
private Socket socket;
public EchoThread(Socket socket){
this.socket=socket;
}
public void run(){
BufferedReader br=null;
PrintWriter pw=null;
try {
//从socket中得到读取流,该流中有客户端发送过来的数据
//InputStreamReader将字节流转化为字符流
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));

pw=new PrintWriter(socket.getOutputStream());
pw.println("客户端发exit/quit结束当前连接;发stop停止服务器\n");
pw.flush();

String info;
while((info=br.readLine())!=null){//行读取客户端数据
System.out.println(info);

pw.println(info);
pw.flush();
if("quit".equals(info) || "exit".equals(info)){
break;

}else if("stop".equals(info)){
bstop=true;
System.exit(0);
break;
}
}

} catch (Exception e) {
e.printStackTrace();
}finally{
try {pw.close();} catch (Exception e) {}
try {br.close();} catch (IOException e) {}
try {socket.close();} catch (IOException e) {}
}
}
}
}