Basic echo server, client-server relationship

岁酱吖の 提交于 2019-12-25 03:05:12

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/22333664/basic-echo-server-client-server-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!