Search code examples
socket.ioserversocket

Server Client Communication on Socket not working bi-directionally


I am new to Socket Programming and very well know that i am making a silly mistake. Unfortunately not able to figure out as to what is going on. I have created a basic multi Client-Server system using Java socket on same machine(shouldn't make any difference), however to my surprise either i am able to only

  • Send Message from Server to Client and then read it on Client. OR
  • Send Message from Client to Server and then read it on Server.

What i am not able to achieve is

  • Send Message from Server to Client and then read it on Client. AND
  • Send Message from Client to Server and then read it on Server.

I am attaching my code.

import java.io.IOException;
import java.net.ServerSocket;

public class ServerSocketMain {

public static void main(String[] args) throws IOException {

    @SuppressWarnings("resource")
    ServerSocket serverSocket = new ServerSocket(1234);

    while(true){
        System.out.println("Server Waiting for Client to Connect ....");
        Thread thread = new Thread(new ServerReaderWriter(serverSocket.accept()));
        System.out.println("Client connected....");
        thread.start();

    }



}

}


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ServerReaderWriter implements Runnable {

private Socket socket;

public ServerReaderWriter(Socket socket) {
    this.socket = socket;
}

@Override
public void run() {
    try {

        readFromClient();
        writeToClient();

    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void writeToClient() throws IOException {
    DataOutputStream writeToClient = new DataOutputStream(this.socket.getOutputStream());
    writeToClient.writeBytes("Communication from Client Thread "
            + Thread.currentThread().getName() + "\n");

}

private void readFromClient() throws IOException {
    BufferedReader inFromClient = new BufferedReader(new InputStreamReader(
            this.socket.getInputStream()));

    System.out.println("Client Communication : " + inFromClient.readLine());

}

}


import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ClientSocketMain {

public static void main(String[] args) throws UnknownHostException, IOException {
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        executorService.submit(new ClientReaderWriter(new Socket("localhost", 1234)));
    }

    executorService.shutdown();

}

}




import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class ClientReaderWriter implements Runnable {

private Socket socket;

public ClientReaderWriter(Socket socket) {
    this.socket = socket;
}

@Override
public void run() {

    try {

        readFromServer(socket.getInputStream());
        writeToServer(socket.getOutputStream());

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

private void writeToServer(OutputStream outputStream) throws IOException {
    DataOutputStream writeToServer = new DataOutputStream(outputStream);

    writeToServer.writeBytes("Communication from Client Thread "
            + Thread.currentThread().getName() + "\n");

}

private void readFromServer(InputStream inputStream) throws IOException {
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
            inputStream));

    System.out.println(inFromServer.readLine());

}

}

I am just wondering if my client socket closes even before read and write operations are done..not sure just guessing out loud. please help!!


Solution

  • As it turned out...i was making a silly mistake....Ordering is very important in the code snippet that i had shared above and i was ignoring the fact.

     readFromClient();
        writeToClient();
    
     readFromServer(socket.getInputStream());
        writeToServer(socket.getOutputStream());
    

    In the above scenario both server and client are trying to read...instead one should be writing and other reading. So all i needed to do was change the order

        writeToClient();
     readFromClient();
    
     readFromServer(socket.getInputStream());
        writeToServer(socket.getOutputStream());