简体   繁体   中英

Client socket is not receiving a string

I have created a simple client server socket program and sending a string a|b|c|* and the client is not recieving it. The client is on another machine.

Server Code.

String format = "a|b|c|*";
ServerSocket ss = new ServerSocket(2222);
System.out.println("Server Started.");

while (true) {              
    Socket s = ss.accept();
    System.out.println("Connection accepted.");
    InputStream is = s.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    PrintStream ps = new PrintStream(s.getOutputStream());
    ps.println(format);             
    ps.flush();
    System.out.println("Format sent.");
}    

Client Side

try {
    Socket s = new Socket("192.168.0.71", 2222);
    // step 3: Get I/O streams
    InputStream is = s.getInputStream();
    InputStreamReader isr= new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String format = br.readLine();
    System.out.println(format);
} catch(Exception ex){
    System.out.println(ex.getMessage());
}

When I create a client on the same machine then it is receiving the string, and when i pass this string to another machine client it doesn't receive it.

So I tried your code on two of my boxes and remote connections worked fine. A bunch of good comments but I thought I'd write out an answer with some things to try:

  1. It's been implied that you've been able to telnet locally to the server and see the format string. Fine. Are you also been able to use telnet from a remote client to the server and also see the format string?

  2. If the remote telnet does not work then I'd check if there is a firewall or otherwise a routing issue. Can you ping the server from the client?

  3. Another reason why telnet might not work is that your server may be binding to the wrong port. The default is to bind to all interfaces but just to be sure, you should check. If you are on a unix box or OSX then you can use the netstat command to see what ports you are binding to. The following output shows that the server is bound to * which means all interfaces.

     $ netstat -an | grep 2222 tcp46 0 0 *.2222 *.* LISTEN 
  4. If nothing else helps then realize that if you have a telnet connected, it will block all other telnets and clients from connecting since you are not closing the socket on the server.

Hope some of this helps.

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