[英]Java socket works only for one client, blocked after server accept
I have a problem with my client/server program, which is blocked after one client is connected. 我的客户端/服务器程序有问题,连接一个客户端后该程序被阻止。 My one client can communicate with my server, but when I try to connect another, the second can't connect. 我的一个客户端可以与我的服务器通信,但是当我尝试连接另一个客户端时,第二个客户端无法连接。 I never see my 'ok' on my console: 我从没在控制台上看到过“ ok”:
public class Server{
private Map<Integer,ThreadClient > mapThreads;
private ServerSocket serveur ;
public static void main(String args[])
{
try{
Serveur serv = new Server();
serv.setServer( new ServerSocket(4786,2));
while (true)
{
serv.getMapThreads().put(new ThreadClient(serv.getServer().accept(),serv);
System.out.println("ok");
}
}
catch (Exception e) { }
}
class ThreadClient implements Runnable
{
private Thread t;
private Socket socket;
private ObjectOutputStream oos ;
private ObjectInputStream ois;
private Serveur server;
public ThreadClient(Socket s, Server serv ) throws ClassNotFoundException
{
server = serv;
socket=s;
try{
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
}
catch (IOException e){ }
t = new Thread(this);
t.start();
}
public void run()
{
try
{
while(true){
// send and recev message
}
}
}
catch (Exception e){ }
}
Move the construction of the object streams out of the constructor and into the run()
method. 将对象流的构造移出构造函数,并移到run()
方法中。 The process implies I/O with the peer so it shouldn't be carried out in the accept()
thread. 该过程暗示与对等方进行I / O,因此不应在accept()
线程中进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.