-1

I have a server-client code which I modified for 2 way communication after I downloaded from internet. I am stuck with server data reception error. When client makes connection, the server replies by sending "Connected to CLIENTIPADDRESS" to client.

Then the client sends "Hi server" message. But I get Socket Exception Error when server tries to read the received message.

I made separate server threads for writing and reading server message. Originally ByteArrayOutputStream was used to read. It didn't work in my case so I use BufferedReader, InputStreamReader and InputStream. I tried to use other input stream reading classes also but I got same socket exception error

The SocketException is : Oops socket error! java.net.SocketException:Socket is closed.

When I checked if the socket is closed/open after writing operation, socket is still open.

I don't know why IO stream reader throws exception. It is always the IO stream buffer in the second thread that generates the error. As far as I know PrintStream does not throw any exception. So although client program is same which first listens and then sends data , no exception is generated by data sending thread which is comes after data receiving thread and so the data is transmitted.

What is wrong here ?

public class MainActivity extends ActionBarActivity {

TextView Info, Infoip, Msg;
String message = "";
ServerSocket serverSocket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Info = (TextView) findViewById(R.id.info);
    Infoip = (TextView) findViewById(R.id.infoip);
    Msg = (TextView) findViewById(R.id.msg);

    Infoip.setText(getIpAddress());

    Thread socketServerThread = new Thread(new SocketServerThread());
    socketServerThread.start();
}

protected void onDestroy() {
    super.onDestroy();

    if (serverSocket != null) {
        try {
            serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private class SocketServerThread extends Thread{
    static final int SocketServerPORT = 8080;
    int count = 0;
    Socket socket;

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(SocketServerPORT);
            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Info.setText("I'm waiting here: "
                            + serverSocket.getLocalPort());
                }
            });

            while (true) {
                socket = serverSocket.accept();

                SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(socket);
                socketServerReplyThread.start();

                ServerReadThread serverReadThread = new ServerReadThread(socket);
                serverReadThread.start();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

public class ServerReadThread extends Thread {
    InputStream is;
    InputStreamReader isr;
    String response = "";
    BufferedReader br;
    Socket hostSocket;

    ServerReadThread(Socket socket){
        hostSocket = socket;
    }

    public void run(){
        try{
            is = hostSocket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            response = br.readLine() + "\n";
            is.close();
            isr.close();
            br.close();

        } catch (IOException e) {
            e.printStackTrace();
            message += "Oops Receiving error! " + e.toString() + "\n";
        }

        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Msg.setText(message);
            }
        });
    }
}

private class SocketServerReplyThread extends Thread {
    private Socket hostThreadSocket;

    SocketServerReplyThread(Socket socket) {
        hostThreadSocket = socket;
    }

    @Override
    public void run() {
        OutputStream outputStream;
        String msgReply = "connected to " + hostThreadSocket.getInetAddress();

        try {
            outputStream = hostThreadSocket.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);
            printStream.print(msgReply);
            printStream.close();

            message += msgReply + "\n";

            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Msg.setText(message);
                }
            });

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            message += "Something wrong! " + e.toString() + "\n";
        }

        MainActivity.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Msg.setText(message);
            }
        });
    }
}

private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += "SiteLocalAddress: "
                            + inetAddress.getHostAddress() + "\n";
                }

            }

        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }
    return ip;
    }
}

The client socket program is :

public class ClientSocket extends Thread {
    String serverAddress;
    int serverPort;
    int homeport;
    Socket socket;
    String response;

    public ClientSocket(String addr, int port){
        serverAddress = addr;
        serverPort = port;
    }

    @Override
    public void run(){  // make connection
        try {
            socket = new Socket(serverAddress, serverPort);

            ClientReadThread clientReadThread = new ClientReadThread(socket);   // client thread for reading
            clientReadThread.run();

            ClientWriteThread clientWriteThread = new ClientWriteThread(socket);
            clientWriteThread.run();

        }  catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
            message = response;
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textResponse.setText(message);
                }
            });
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
            message = response;
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textResponse.setText(message);
                }
            });
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

In both server and client, reading and writing functions are similar

sujan_014
  • 516
  • 2
  • 8
  • 22
  • If you get an exception you should post it here. Not paraphrase it and then try something else to get around it and then ask why the workaround doesn't work. Start at the beginning. – user207421 Jul 16 '15 at 08:35

1 Answers1

0

When you comment out the try and catch blocks, the code no longer compiles, so it doesn't execute, so of course you don't get any exceptions, or data.

Your question doesn't make sense.

However you have several other errors in your code:

  1. You should be calling start(), not run(). Otherwise no thread is created.
  2. read() will block until data is available. Calling the available() method as you are doing is pointless, and using it as a test for end of message or end of stream is incorrect: see the Javadoc.
user207421
  • 305,947
  • 44
  • 307
  • 483