简体   繁体   中英

Simple Client-Server Communication?

Working on a server-socket lab in Java and our instructor provided us with the Client Side of the code. In the project, Client sends a string to the server. The Server then turns around and sends the string back to the client.

Client

        Socket server = new Socket(host, 30000); 

        // Sends the string to the Server
        Socket server = new Socket(host, 30000);
        OutputStream serverOut = server.getOutputStream();
        PrintWriter serverWrite = new PrintWriter(serverOut, true);
        serverWrite.println("Bryce");


        //Manages Server's response of "Hello, Bryce!"
        InputStream serverIn = server.getInputStream();
        Scanner serverScan = new Scanner(serverIn);
        serverScan.useDelimiter("$");
        String resp = serverScan.next();

Server

    ServerSocket ss = new ServerSocket(30000);
    Socket s = ss.accept();
    InputStream is = s.getInputStream();


     // Gets Message from Client
    InputStreamReader reader = new InputStreamReader(is);
    BufferedReader readerBuff = new BufferedReader(reader);
    String stringFromClient = readerBuff.readLine();


     // Sends Message back to Client
     OutputStream oos = s.getOutputStream();
     PrintWriter pl = new PrintWriter(oos, true);
     pl.println("Hello, " + stringFromClient + "!");

EverytimeI run the program, it pulls up a NoSuchElementException and cites the offending line in Client:

String resp = serverScan.next();

This should be a fairly simple problem(I've completed this sort of problem before). If i replace

 String resp = serverScan.next();

with

 String resp = serverScan.toString();

it works fine, but as I'm not allowed to modify the Client-Code, I'm totally confused. Am I missing something here?

In the client side code, you have

serverScan.useDelimiter("$");

This means the client side scanner will use $ as the delimiter for the incoming characters. So in order to let client side know that a complete tokenized string is sent, you need to add one more character at the end of the message string sent by server:

pl.println("Hello, " + stringFromClient + "!" + "$");

The javadoc of next method in Scanner class says:

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

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