java ServerSocket.accept没有响应[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我的代码有问题。 serverSocket不起作用后的代码,这意味着一旦到达serverSocket.accept就会被挂起。

import java.io.*;
import java.net.*;
public class AppChat {

    String[] list = { 
        "Take me ", 
        "the code", 
        "Hello from the other side", 
        "the man ",
        "what can we do?", 
        "that is all for today" 
        };

    void go() {
        try {
            ServerSocket serverSocket = new ServerSocket(53439);
            boolean t = true;
            while (true) {
                System.out.println("i am about to execute serverSocket");

一切都工作到这个位置,但在这之后,这个代码是库存.accept。请问,我做错了什么因为我试图寻求理解,但仍然没有找到正确的答案。

                Socket socs = serverSocket.accept();// everything is stocked here
                System.out.println("unfortunatly the serverSocket.accept is hoding all the goodies");
                PrintWriter wr = new PrintWriter(socs.getOutputStream());
                String advce = getAdvice();
                wr.println(advce);
                wr.close();
                System.out.println(advce);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getAdvice() {
        int randdon = (int) (Math.random() * list.length);
        // System.out.println(list[randdon]);
        return list[randdon];
    }

    public static void main(String[] args) {
        AppChat app = new AppChat();
        app.go();
        app.getAdvice();
    }
}
java sockets serversocket
1个回答
0
投票

ServerSocket#accept()阻止,直到它从客户端获得传入连接。如果没有客户端连接,该行将无限阻塞。

© www.soinside.com 2019 - 2024. All rights reserved.