Why server didn't see the clients sending data?

问题: The class Server must contain all necessary code for starting a server service, managing socket connections and holding bet history data. After Server.start() has been run,...

问题:

The class Server must contain all necessary code for starting a server service, managing socket connections and holding bet history data. After Server.start() has been run, the server must be listening to incoming socket connections on the given port and be able to handle multiple socket connections concurrently, using multi-threading or some other mechanism. Why on the serverSocket.accept() happens nothing ?

public class Server {
    public Socket socket;
    public DataInputStream in;
    public PrintWriter out;
    public int serverSocketPort;
    public ServerSocket serverSocket;


    public Server(int serverSocketPort) throws IOException {

        this.serverSocket = new ServerSocket(serverSocketPort);
        System.out.println("Server started");

    }

    public void start() {

        try {
            serverSocket.accept();
            System.out.println("Client accepted");

            in = new DataInputStream(
                    new BufferedInputStream(socket.getInputStream()));

            String line = "";

            while (!line.equals("Over")) {
                try {
                    line = in.readUTF();
                    System.out.println(line);

                } catch (IOException i) {
                    System.out.println(i);
                }
            }

            // close connection
            socket.close();
            in.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }


回答1:

serverSocket.accept();

blocks until a socket is connected.

Socket s = serverSocket.accept();

in = new DataInputStream(new BufferedInputStream(s.getInputStream()));

OR

socket = serverSocket.accept();
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

EDIT - 29.03.2019 11.54

So we know:

serverSocket.accept();

blocks your thread. You call it in your main thread.

...
successfulThreads = new AtomicInteger(0);
latch = new CountDownLatch(testcaseThreads);
gate = new CyclicBarrier(testcaseThreads + 1);

server = new Server(SOCKET_PORT);
server.start();  //<-- Your program blocks!!!
//  ||
//  || STOP! No execution of the code.
// \//
//  /
for (File testcaseFile : testcaseFiles) {
            new Thread(new MockClient(this, testcaseFile)).start();
}
  • 发表于 2019-03-31 02:14
  • 阅读 ( 164 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除