0

So as my project I had to write a client class and a simple server class that will ECHO message written by the client.

For some reason I either get I/O exception or a loop of exceptions that socket's closed.

I would really appreciate some help, because I struggle with this program for 2 days straight and cannot find any solutions.

My Server class:

import java.io.*;
import java.net.*;
import java.util.regex.Pattern;

public class SimpleServer {
    private ServerSocket ss = null;
    private BufferedReader in = null;
    private PrintWriter out = null;

public SimpleServer(String host, int port) {
    try {
    InetSocketAddress isa = new InetSocketAddress(host, port);
    ss = new ServerSocket();
    ss.bind(isa);
    } catch (IOException exc) {
        System.out.println("Error in constructor");
        System.exit(1);
    }
    System.out.println("Server started.");
    System.out.println("on port: " + ss.getLocalPort());
    System.out.println("bind address: " + ss.getInetAddress());
    serviceConnections();       
}//constructor

private void serviceConnections() {     
    boolean serverRunning = true;

    while(serverRunning) {
        try {
            Socket conn = ss.accept();
            System.out.println("Connection established!");
            serviceRequests(conn);              
        } catch (Exception exc) {
            exc.printStackTrace();
        }

        try { ss.close(); } catch (Exception exc) {}
    }       
}//serviceConnections

private void serviceRequests(Socket connection) throws IOException {
    try {
        in = new BufferedReader(new      InputStreamReader(connection.getInputStream()));
        out = new PrintWriter(connection.getOutputStream(), true);
        String line = in.readLine();            
        out.println(line);
    } catch (Exception exc) {
        exc.printStackTrace();
    } finally {
        try {
            in.close();
            out.close();
            connection.close();
            connection = null;
        } catch(Exception exc) {}
    }
}//serviceReq       

public static void main(String[] args) {

    String host = "localhost";
    int port = 2401;            
    new SimpleServer(host,port);        
}//main 
}//class

My client class:

import java.net.*;
import java.io.*;


public class SimpleServerClient {

    private Socket sock = null;
    private PrintWriter out = null;
    private BufferedReader in = null;

public SimpleServerClient (String host, int port) {     
    try {
        sock = new Socket(host, port);
        out = new PrintWriter(sock.getOutputStream(),true);
        in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    //  System.out.println("Connected to the: " + sock.getInetAddress() );
        makeRequest("ECHO Howdy boy");      


    } catch (UnknownHostException e) {
        System.err.println("Unknown host: "+host);
        System.exit(2);
    } catch (IOException e) {
        System.err.println("I/O error for");
        System.exit(3);
    } catch (Exception exc) {
        exc.printStackTrace();
        System.exit(4);
    }
}//constructor

private void makeRequest(String req) throws IOException {
    System.out.println("Request: " + req);
    out.println(req);
    String resp = in.readLine();
    System.out.println(resp);
    disconnect();
}//method

public void disconnect() {
    try {
    out.close();
    sock.close();
    in.close();     
    } catch(IOException exc) {
        System.out.println("Error while closing");
        System.exit(5);
    }
}//method

public static void main(String[] args) {
    new SimpleServerClient("localhost", 2401);
}//main
}//class
justMe
  • 674
  • 7
  • 26

2 Answers2

0

The way it (should) work:

Server opens ServerSocket and accept connections on that ServerSocket.
Every connection (new client) [should be handled in separate thread] is a separate new Socket connection with it's own I/O channels.
For each new Socket you should open I/O channels once and keep them open until the client disconnects.

If you follow this logic everything will work.

Germann Arlington
  • 3,315
  • 2
  • 17
  • 19
  • But in this case in my SimpleServerClass I only have 1 Socket and I/O channels are opened before request from the client is read and also closed after hi finishes. – justMe Mar 11 '14 at 18:54
0

I have already shared a nice Chat Program having one server that is communicating with multiple clients using TCP protocol.

Please have a look at Java Server with Multiclient communication.

It might help you. Meanwhile I am looking your code.

In you code you have closed the socket after connected with single client.

Here is the fix:

private void serviceConnections() {
    boolean serverRunning = true;

    while (serverRunning) {
        try {
            Socket conn = ss.accept();
            System.out.println("Connection established!");
            serviceRequests(conn);
        } catch (Exception exc) {
            exc.printStackTrace();
        }

    }
    try {
        ss.close();
    } catch (Exception exc) {
    }
}// serviceConnections
Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • Your program is bit more complicated as it's multi-threaded. I have yet compared those parts that in both cases should be similar(or almost exactly same) and I cannot find any bloody mistakes in my code. – justMe Mar 11 '14 at 19:31
  • Its working fine if `while` is replace with `if` in `SimpleServer.serviceConnections()` method. It means just after connecting with single client, server is also stopped. If you want to have multiple client connected with single server then try my program. Its very simple. You need to use threading in case of multiple client connection if client also needs to be communicated with each other. – Braj Mar 11 '14 at 19:38
  • Finally I have found the reason. I have updated my answer, please try it now. – Braj Mar 11 '14 at 19:44
  • My next assignment's going to regard multi-threading. For that I shall study your lecture. Thank you VERY much for help as it was literally pain in the butt. – justMe Mar 11 '14 at 19:45
  • Your most welcome and Welcome in the world of Multi-threading. – Braj Mar 11 '14 at 19:47