Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Server connection should work like this:</p> <pre><code>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(); } } </code></pre> <p>In hanleConnection() you start a new thread and run the communication for this client in the created thread. Then the server can accept a new connection (in the old thread).</p> <pre><code>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 } </code></pre> <p>The PlayerConnection class:</p> <pre><code>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) {} } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload