多个客户同时连接ServerSocket的简单实现

当一个 Socket 会话产生后或者说服务器端SeverSocket接收了Socket后,将这个sokcet会话交给线程处理,然后主程序继续监听。运用 Thread 类或 Runnable 接口来实现是不错的办法。  


具体的代码如下:

服务器Socket

*****************************************************************************

public class Server extends ServerSocket {
    private static final int SERVER_PORT = 10000;
public Server() throws IOException {
super(SERVER_PORT);
try{
System.out.println("启动服务器");
while(true){
  Socket socket = this.accept();
 
  new ServerThread(socket);//每当收到一个socket就创建一个线程
}
}catch(IOException e){
e.printStackTrace();
}

finally{
this.close();
}
}

public static void main(String args[]) throws IOException{
     new Server();
    }

}

****************************************************************************************************

线程类

public class ServerThread extends Thread{
    private Socket client;
private BufferedReader in;
public ServerThread(Socket client) {
super();
this.client = client;
try {

this.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {

try {
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));// 得到客户端的输入流
System.out.println(in.readLine());//控制台输入信息
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
    
    
    
    
}

**********************************************************************************************************

客户端类

public class Client {


private Socket socket;
private PrintWriter out;//相当于向外写文件,所以用out
    private static int count = 1;
public Client(String clientName) {
this.connect();


}


public Client() {
this(null);
this.connect();
}


public void connect() {
try {
socket = new Socket("127.0.0.1", 10000);
System.out.println("请输入信息:");
out = new PrintWriter(socket.getOutputStream(), true);


BufferedReader line = new BufferedReader(new InputStreamReader(
System.in));// 从控制台输入信息


out.println(line.readLine());// 输入信息到服务器
out.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


/**
 * @param args
 */
public static void main(String[] args) {
new Client();


}


}

****************************************************************************************

测试方法,先运行Server,再运行Client

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭梧悠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值