user5100681
user5100681

Reputation:

Send and Receive data Simultaneously via Sockets

I'm working on a little game that sends location data between a client an server to learn how Sockets work.

The server can send and receive data no problem, and the client can send data, but when the client tries to read in data from the server, the program hangs. (This part is commented out)

Server Code:

public void run() {

    try {
        serverSocket = new ServerSocket(10007);
    } catch (IOException e) {
        System.err.println("Could not listen on port: 10007.");
        System.exit(1);
    }

    try {
        System.out.println("Waiting for connection...");
        clientSocket = serverSocket.accept();
    } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
    }
    System.out.println("Connection successful");
    System.out.println("Waiting for input.....");
    while (true) {
        try {
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            if (in.readLine() != "0" && in.readLine() != null) {
                setXY(in.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        out.println("X" + Graphics.charX);
        out.println("Y" + Graphics.charY);
    }

Client Code:

public void run() {

    try {
        System.out.println("Attemping to connect to host " + serverHostname + " on port " + serverPort + ".");
        echoSocket = new Socket(serverHostname, serverPort);
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: " + serverHostname);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
        System.exit(1);
    }
    while (true) {

        try {
            in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            /*if (in.readLine() != "0" && in.readLine() != null) {
                setXY(in.readLine());
            }*/
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        out.println("X" + Graphics.charX);
        out.println("Y" + Graphics.charY);

    }

}

Any help is much appreciated!

Upvotes: 2

Views: 2117

Answers (1)

Darth Android
Darth Android

Reputation: 3502

You need two threads to read/write blocking sockets at the same time (which is what you're trying to do). When you call in.readLine(), the current thread will block until it receives a line of data.

Upvotes: 3

Related Questions