2011-10-05 89 views
1

我在课堂上正在设计一个小游戏时遇到问题。 问题是我有两个客户端连接到服务器。 (client1和client2)他们每个人都在运行一个游戏,最后关闭窗口。由于游戏窗口是一个JDialog,它将在关闭时通过套接字发送一条消息到服务器,告诉它已完成。我希望服务器知道哪两个客户端先完成。他们通过套接字的OutputStream上的PrintWriter进行报告。 我所做的就是这样的:在多个套接字(InputStreamReader)上进行监听

in1 = new BufferedReader(new InputStreamReader(client.getInputStream())); 
    in2 = new BufferedReader(new InputStreamReader(client2.getInputStream())); 
    try { 
     in1.readLine(); 
    } catch (IOException ex) { 
     Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    try { 
     in2.readLine(); 
    } catch (IOException ex) { 
     Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex); 
    } 

问题是,它等待第一个输入,它甚至开始监听前一秒。我怎样才能让它同时收听?或者用其他方式解决我的问题。 谢谢!

+2

如果你想同时做多件事情,而不是有一个等待对方,这是使用线程的理想时机。 –

回答

7

服务器连接应该像这样工作:

Server gameServer = new Server(); 

ServerSocket server; 
try { 
    server = new ServerSocket(10100); 
    // .. server setting should be done here 
} catch (IOException e) { 
    System.out.println("Could not start server!"); 
    return ; 
} 

while (true) { 
    Socket client = null; 
    try { 
     client = server.accept(); 
     gameServer.handleConnection(client); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

在hanleConnection()开始一个新的线程并运行该客户端所创建的线程的通信。然后服务器可以接受一个新的连接(在旧线程中)。

public class Server { 
    private ExecutorService executor = Executors.newCachedThreadPool(); 

    public void handleConnection(Socket client) throws IOException {  
     PlayerConnection newPlayer = new PlayerConnection(this, client); 
     this.executor.execute(newPlayer); 
    } 

    // add methods to handle requests from PlayerConnection 
} 

的PlayerConnection类:

public class PlayerConnection implements Runnable { 

    private Server parent; 

    private Socket socket; 
    private DataOutputStream out; 
    private DataInputStream in; 

    protected PlayerConnection(Server parent, Socket socket) throws IOException { 
     try { 
      socket.setSoTimeout(0); 
      socket.setKeepAlive(true); 
     } catch (SocketException e) {} 

     this.parent = parent; 
     this.socket = socket; 

     this.out = new DataOutputStream(socket.getOutputStream());; 
     this.in  = new DataInputStream(socket.getInputStream()); 
    } 

    @Override 
    public void run() {     
     while(!this.socket.isClosed()) {       
      try { 
       int nextEvent = this.in.readInt(); 

       switch (nextEvent) { 
        // handle event and inform Server 
       } 
      } catch (IOException e) {} 
     } 

     try { 
      this.closeConnection(); 
     } catch (IOException e) {} 
    } 
} 
+0

我不确定我完全理解。我的客户都已经连接到我的服务器,问题是要找出谁先回复服务器,告诉他们已完成。 – Martin

+1

是的,但似乎你处理它不是最好的。如果您有两个线程运行到客户端的连接;您可以同时监听两个流,并通知服务器哪个连接首先响应。 – MasterCassim

+0

“你可以同时听两个流,并通知服务器哪个连接首先响应。” 是的,这是我想要的,但我该怎么做呢? :P 感谢btw,为您的答复! :) – Martin