简体   繁体   中英

Not able to run multithreaded server program in Java

Here is the server code

package echoserver;

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

public class EchoServer {

    public static void main(String[] args) {
        try {

            //establish server socket
            ServerSocket s = new ServerSocket(1981);

            //Thread client connectionsincoming
            while (true) {
                //wait for incoming connection
                Socket incoming = s.accept();
                Runnable r = new ThreadedEchoHandler(incoming);
                Thread t = new Thread(r);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


package echoserver;

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

class ThreadedEchoHandler implements Runnable {

    public ThreadedEchoHandler(Socket i) {
        //initializing socket
        incoming = i;
    }

    public void run() {
        try {
            try {
                //recieve input stream from socket
                InputStream inStream = incoming.getInputStream();

                //recieve output stream from socket
                OutputStream outStream = incoming.getOutputStream();

                //Create a scanner from input stream
                Scanner scan = new Scanner(inStream);

                //Create printer writer from output stream and enabled auto flushing
                PrintWriter out = new PrintWriter(outStream, true);

                //prompt users on how to exit program soon as a long in into the server
                out.println("Enter BYE to exit");

                boolean done = false;

                //while done is not true and scanner has next line loop
                while (!done && scan.hasNextLine()) {

                    //reading text that came in from the socket
                    String line = scan.nextLine();

                    //On the server print the ip address of where the text is coming from and the text they typed
                    System.out.println("Recieved from " + incoming.getInetAddress().getHostAddress() + ": " + line);

                    //Echo back the text the client typed to the client
                    out.println("Echo: " + line);

                    //if they type BYE in caps terminate there connection and I also trimmed whitespaces
                    if (line.trim().equals("BYE")) {
                        done = true;
                    }
                }
            } //finally close the socket connection
            finally {
                incoming.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private Socket incoming;
}

and here is the code for client

package client;

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

public class Client {

    public static void main(String[] args) throws IOException {
        PrintWriter out = null;
        try {
            Socket s = new Socket(InetAddress.getLocalHost(), 1981);
            System.out.println("Connected to server on port 1981");
            out = new PrintWriter(s.getOutputStream());

            out.println("Hello");
            s.close();

        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
    }
}

Socktes are getting created successfully but when control goes to t.start() method call it is not calling run() method of ThreadedEchoHandler class.

Why is this happening? any idea?

The client writes "Hello" to the PrintWriter . So far, so good.

You may expect that the PrintWriter sends this text directly to the socket, but it doesn't. The documentation from the PrintWriter(OutputStream) constructor says that it creates a PrintWriter without automatic line flushing . This means that you have to call out.flush() whenever you want something to be actually sent.

Until you call out.flush() the text only exists in some internal buffer, and the server will not be able to see it.

My guess would be that the acept statement is blocking forever because no client is connecting to the server. You could wrap accept() in prints to prove or disprove.

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