简体   繁体   中英

Socket won't accept the strings

This is my code:

public class EchoServer {

    ServerSocket ss;
    Socket s;
    DataInputStream din;
    DataOutputStream dout;

    public EchoServer() 
    {
        try
        {
            System.out.println("server started");
            //ss = new ServerSocket(0);
            //System.out.println("listening on port: " + ss.getLocalPort());
            ss = new ServerSocket(49731);
            s = ss.accept();
            System.out.println(s);
            System.out.println("connected");
            din = new DataInputStream(s.getInputStream());
            dout = new DataOutputStream(s.getOutputStream());
            Server_chat();
            ss.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        new EchoServer();
    }

    public void Server_chat() throws IOException {

        String str;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in ));
        do
        {
            System.out.println("enter a string");
            str = br.readLine();
            System.out.println("str " + din.readUTF());
            dout.flush();            
        }
        while(!str.equals("stop"));
    }
}

I verified 49731 port by passing port no. 0 earlier and got this port.

When I run the above code on Netbeans the output shows "server started" and then it keeps on running even though it should show connected and rest of the input I provide.

And then it keeps on running even though it should show connected and rest of the input I provide.

Why it should go on printing 'connected'?

s=ss.accept();

In this line you are: listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.

accept method will wait for a client that connect to him. So you need to provide a client that connect to the server. Otherwise he'll wait forever!

For some examples about how to use socket in java see here and here .

For more about accept() read here

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