简体   繁体   中英

socket.accept() does not execute

I have this code, wich i just download it.

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

public class Server {
 public static void main(String argv[]) throws Exception
 {
    String clientSentence;
    String capitalizedSentence;
    ServerSocket welcomeSocket = new ServerSocket(6060);

    while(true)
    {
       Socket connectionSocket = welcomeSocket.accept();
       System.out.println("ssss");
       BufferedReader inFromClient =
          new BufferedReader(new  InputStreamReader(connectionSocket.getInputStream()));
       DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
       clientSentence = inFromClient.readLine();
       System.out.println("Received: " + clientSentence);
       capitalizedSentence = clientSentence.toUpperCase() + '\n';
       outToClient.writeBytes(capitalizedSentence);
    }
}

}

First it ran so well then when i tried to run it back it runs but it does not reach to the print statement :

System.out.println("ssss");

it stops on welcomeSocket.accept();

Even i tried an old server code that i used before it also did not run and stopped in the same part however , it ran from the linux terminal.

It's working as intended. The .accept() function is a blocking function, meaning that .accept() waits for a connection attempt and will hold your code there.

If you make a connection to your server, it'll move past that point, print sss once, and after executing the rest of the while loop, be stuck there again until you make a new connection.

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