M
M
mr_blond972017-06-25 20:21:49
Java
mr_blond97, 2017-06-25 20:21:49

How can I change the example so that the server waits for the client to connect?

I'm going through an example with websockets in libgdx. I comment on the part of the code in which the client is created:

public class PingPongSocketExample extends GdxTest {
  @Override
  public void create () {
    // setup a server thread where we wait for incoming connections
    // to the server
    new Thread(new Runnable() {
      @Override
      public void run () {
        ServerSocketHints hints = new ServerSocketHints();
        ServerSocket server = Gdx.net.newServerSocket(Protocol.TCP, "localhost", 9999, hints);
        // wait for the next client connection
        Socket client = server.accept(null);
        // read message and send it back
        try {
          String message = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
          Gdx.app.log("PingPongSocketExample", "got client message: " + message);
          client.getOutputStream().write("PONG\n".getBytes());
        } catch (IOException e) {
          Gdx.app.log("PingPongSocketExample", "an error occured", e);
        }
      }
    }).start();

    // create the client send a message, then wait for the
    // server to reply
    // 		SocketHints hints = new SocketHints();
    // 		Socket client = Gdx.net.newClientSocket(Protocol.TCP, "localhost", 9999, hints);
    // 		try {
    // 			client.getOutputStream().write("PING\n".getBytes());
    // 			String response = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
    // 			Gdx.app.log("PingPongSocketExample", "got server message: " + response);
    // 		} catch (IOException e) {
    // 			Gdx.app.log("PingPongSocketExample", "an error occured", e);
    // 		}
  }
}

The server waits for a client to connect for a few seconds and throws an exception:
Exception in thread "Thread-7" com.badlogic.gdx.utils.GdxRuntimeException: Error accepting socket.
  at com.badlogic.gdx.backends.lwjgl.LwjglServerSocket.accept(LwjglServerSocket.java:83)
  at HelloWorldWebsocket.WebsocketClient$1.run(WebsocketClient.java:44)
  at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.SocketTimeoutException: Accept timed out
  at java.net.PlainSocketImpl.socketAccept(Native Method)
  at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)
  at java.net.ServerSocket.implAccept(ServerSocket.java:545)
  at java.net.ServerSocket.accept(ServerSocket.java:513)
  at com.badlogic.gdx.backends.lwjgl.LwjglServerSocket.accept(LwjglServerSocket.java:80)

How to change the example so that the server waits indefinitely for the client to connect?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question