简体   繁体   中英

Client-Server TCP communication

The server should send a message "Hello:: enter QUIT to exit" to the client, then the client types in any text and the server echos back the client's text adding "From server: " before their message. But there seems to be a mix up in the order and I can't seem to find where! I've been on this all day!

This is the Server's code:

    import java.net.*;


public class Server {

    public static void main(String[] args) {

        int nreq = 1;
        try
        {
            ServerSocket sock = new ServerSocket (8080);
            for (;;)
            {
                Socket newsock = sock.accept();
                System.out.println("Creating thread ...");
                Thread t = new ThreadHandler(newsock,nreq);
                t.start();
            }
        }
        catch (Exception e)
        {
            System.out.println("IO error " + e);
        }
        System.out.println("End!");
    }
}

ThreadHandler code:

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

class ThreadHandler extends Thread {
    Socket newsock;
    int n;

    ThreadHandler(Socket s, int v) {
        newsock = s;
        n = v;
    }

    // @SuppressWarnings("deprecation")
    public void run() {
        try {

            PrintWriter outp = new PrintWriter(newsock.getOutputStream(), true);
            BufferedReader inp = new BufferedReader(new InputStreamReader(
                    newsock.getInputStream()));
            outp.println("Hello :: enter QUIT to exit");
            boolean more_data = true;
            String line;
            while (more_data) {
                line = inp.readLine();
                if (line == null) {
                    more_data = false;
                } else {
                    outp.println("From server: " + line + "\n");
                    if (line.trim().equals("QUIT"))
                        more_data = false;
                }
            }
            newsock.close();
        } catch (Exception e) {
            System.out.println("IO error " + e);
        }

    }
}

And the Client code:

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

public class Client {
    // @SuppressWarnings("deprecation")
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        try {
            Socket s = new Socket("localhost", 8080);
            PrintWriter outp = new PrintWriter(s.getOutputStream(), true);
            BufferedReader inp = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));
            boolean more_data = true;
            System.out.println("Established connection");
            String line;
            while (more_data) {
                line = inp.readLine();
                String userInput = scanner.nextLine();
                outp.println(userInput);
                if (line == null) {
                    more_data = false;
                } else
                    System.out.println(line);
            }
            System.out.println("end of while");
        } catch (Exception e) {
            System.out.println("IO error " + e);
        }
    }
}

I'm testing it out so after I'm going to make the client an Android phone - if that's possible -


Update:

I've changed the server's code to:

outp.println("Hello :: enter QUIT to exit \n");
        boolean more_data = true;
        String line;
        while (more_data) {
        line = inp.readLine();
        System.out.println("Message '" + line + "' echoed back to client.");// !!
        if (line == null) {
            System.out.println("line = null");
            more_data = false;
        } else {
            outp.println("From server: " + line + ". \n");
            if (line.trim().equals("QUIT"))
                more_data = false;
        }
    }
    newsock.close();
    System.out.println("Disconnected from client number: " + n);

and added "\n" at the end of the Hello message as Luis Miguel Serrano suggested, And changed the Client's side as below:

boolean more_data = true;
        System.out.println("Established connection");
        String line;// = inp.readLine();

        while (more_data) {
            line = inp.readLine();
            System.out.println(line);
            if (line == null) {
                // nothing read
                more_data = false;
            } else
                line = inp.readLine();
            System.out.println(line);
            String userInput = scanner.nextLine();
            if (userInput.trim() == "QUIT") {
                s.close();
                System.out.println("Disconnected from server.");
                more_data = false;
            } else
                outp.println(userInput);

        }
        System.out.println("end of while");

And it works fine now.

If anyone could suggest me some Android client-java server tutorials would appreciate it.

In sequence of your comment, it could be a flushing issue. Try adding the following line:

outp.flush();

after:

outp.println("Hello :: enter QUIT to exit");

When you write to a stream, sometimes the things you write are kept in a buffer. If you want to make sure that buffer is emptied and the string is actually sent, you need to call the flush() method.

Update

Also, add "\n" to the end of your Hello welcome message from the server. I think that will make it work.

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