简体   繁体   中英

Server not receiving requests from client

Basically I'm writing a 2 way communication client server program. The client sends requests to the server and server responds accordingly. The requests have to do with adding or removing tokens from a list of tokens stored on the server. The client side seems to work fine, the requests are being sent to the server. However it seems that the server is not receiving any request from the client and I have no idea why. I've attached the code:

client

package;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TokenClient {

    private static final int PORT_NUMBER = 9999;

    private Socket socket;

    private InputStream inStream;

    private OutputStream outStream;

    private Scanner inStreamScanner;

    private PrintWriter outStreamPrinter;

    public static void main(String[] args) {

        new TokenClient().go();

    }

    void go() {

        try {

            System.out.println(
                    "Enter commands of the form \"CONNECT IP-address\", \"SUBMIT token\", \"REMOVE token\" or \"QUIT\"\n");

            Scanner consoleScanner = new Scanner(System.in);
            // java.io.BufferedReader consoleInputReader = new
            // BufferedReader(new InputStreamReader(System.in));

            String command = "";

            while (!command.equals("QUIT") && consoleScanner.hasNextLine()) {

                command = consoleScanner.nextLine(); // consoleInputReader.readLine();

                processCommand(command);

            }

            System.out.println("Goodbye!");

            consoleScanner.close();

        } catch (IOException e) {

            System.out.println("An exception occurred: " + e);

            e.printStackTrace();

        }

    }

    void processCommand(String userCommand) throws IOException {

        if (userCommand.startsWith("SUBMIT"))  

            sendMessageToServer(userCommand);

        else if (userCommand.startsWith("REMOVE"))

            sendMessageToServer(userCommand);

        else if (userCommand.equals("QUIT"))

            closeConnectionToServer();

        else if (userCommand.startsWith("CONNECT")) {

            closeConnectionToServer();

            connectToServer(userCommand);

        } else
            System.out.println("Invalid user command: " + userCommand);

    }

    void closeConnectionToServer() {

        if (socket != null && !socket.isClosed()) {

            try {

                System.out.println("Disconnecting from server...");

                sendMessageToServer("QUIT");

                socket.close();

                System.out.println("Connection to server closed.");

            } catch (IOException e) {
                System.out.println("An exception occurred: " + e);
                e.printStackTrace();
            }
        }
    }

    void connectToServer(String connectCommand) throws IOException {
        String ipAddress = connectCommand.substring(8).trim();
        System.out.println("Connecting to server at " + ipAddress + ", port " + PORT_NUMBER + "...");
        socket = new Socket(ipAddress, PORT_NUMBER);
        inStream = socket.getInputStream();
        outStream = socket.getOutputStream();
        inStreamScanner = new Scanner(inStream);
        outStreamPrinter = new PrintWriter(outStream);
        System.out.println("Connected to server.");

    }

    void sendMessageToServer(String command) {

        System.out.println("Sending message to server: " + command + "...");

        if (socket == null || socket.isClosed())
            System.out.println("Not possible - not connected to a server");
        else {

            outStreamPrinter.println(command); // send the message to the server

            // NB: client doesn't check if tokens are valid

            outStreamPrinter.flush(); // do so immediately

            // Receive response from server:

            if (!command.equals("QUIT") && inStreamScanner.hasNextLine()) {
                String response = inStreamScanner.nextLine();
                System.out.println("Response from server: " + response);
            }
        }
    }
}

server

package;

import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;

public class server {
    private static Socket s;
    private static Scanner inStreamScanner;
    private static int PORT_NUMBER = 9999;
    private static InputStream inStream;
    private static OutputStream outStream;
    private static PrintWriter outStreamPrinter;
    private static ArrayList<String> ts = new ArrayList<String>();
    public static void main(String[] args) throws IOException{
        ServerSocket ss = new ServerSocket(PORT_NUMBER);
        server serverInstance = new server();
        server.s = ss.accept();
        System.out.println("Client connected");
        inStream = s.getInputStream();
        outStream = s.getOutputStream();
        inStreamScanner = new Scanner(inStream);
        outStreamPrinter = new PrintWriter(outStream);
        serverInstance.run();
    }
    public void run() {
        try {
            try {
                doService();
            } finally {
                s.close();
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }
    public void doService() throws IOException{
        while(true) {
            if(inStreamScanner.hasNext())
                return;
            else {
                outStreamPrinter.println("NO REQUEST");
                outStreamPrinter.flush();
            String request = inStreamScanner.next();
            outStreamPrinter.println("Request received: " +request);
            outStreamPrinter.flush();
            handleServerRequest(request);
        } 
        }
    }
    public void handleServerRequest(String request) throws IOException{
        if(request.startsWith("SUBMIT")) {
            String token = extractNum(request);
            addtoTS(token);
        } else if(request.startsWith("REMOVE")) {
            String token = extractNum(request);
            removefromTS(token);
        } else if(request.startsWith("QUIT")) {
            s.close();
        } else {
            outStreamPrinter.println("UNKNOWN REQUEST");
            outStreamPrinter.flush();
        }
    }
    public String extractNum(String request) {
        String str = request;
        String numberOnly = str.replaceAll("[^0-9]", " ");
        return numberOnly;
    }
    public void addtoTS(String token) {
        if(ts.contains(token)) {
            outStreamPrinter.println("OK");
            outStreamPrinter.flush();
        }else {
            ts.add(token);
            outStreamPrinter.println("OK");
            outStreamPrinter.flush();
        }
    }
    public void removefromTS(String token) {
        if(ts.contains(token)) {
            ts.remove(token);
            outStreamPrinter.println("OK");
            outStreamPrinter.flush();
        }else {
            outStreamPrinter.println("ERROR: TOKEN NOT FOUND");
            outStreamPrinter.flush();
        }
    }
}

I haven't run the code, but there seems to be an issue in your doService() method on the server side. You have an infinite loop, but the entire method returns (and thus the program also quits) as soon as the input stream recieves a new line character (when the client sends a request). So, it seems your program would quit when it receives the first command from the client. I'd also recommend closing more gently (ie check in the loop for end rather than closing the socket directly).

So, I'd define a private class variable boolean listening; or something like that. Then in the main() method, set it to true after the socket has been initialized (when the client has connected).

Change your doService() to something similar to the following:

public void doService() throws IOException
{
  while(listening)
  {
    if(inputStreamReader.hasNext())
    {
      String request = inStreamScanner.next();
      outStreamPrinter.println("Request received: " +request);
      outStreamPrinter.flush();
      handleServerRequest(request);
    }
  }
}

And change how you handle the QUIT command:

from

else if(request.startsWith("QUIT"))
{
  s.close();
}

to

else if(request.startsWith("QUIT"))
{
  listening = false;
}

The socket will be closed by the finally in run() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM