为什么我的ServerSocket不接受我的客户端连接请求?

时间:2019-11-30 09:42:38

标签: java sockets server client

我已经在本地计算机上创建了服务器类,并尝试使用客户端线程连接到该服务器类。由于某些原因,当我运行客户端代码时,应用程序在服务器构造函数中的socket.accept()处暂停进程。我确保端口号相同,并且主机名是localhost。知道为什么会这样吗?

public class Client extends Thread {    
    private ObjectInputStream dataIn;
    private ObjectOutputStream dataOut;
    boolean playing = true; 
    public Client(String host, String port) {
        try(Socket sock = new Socket(host, Integer.parseInt(port)) {
            dataIn = new ObjectInputStream(sock.getInputStream());
            dataOut = new ObjectOutputStream(sock.getOutputStream());
            this.start();
            Scanner sc = new Scanner(System.in);
            while(playing) {
                String event = sc.nextLine().trim();
                dataOut.writeObject(event);
                dataOut.flush();
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
    public static void main(String [] args) {
        //retrieves info from content of user-specified file
        Configuration config = new Configuration();
        config.configureFile();
        Client cl = new Client(config.getParamValue("ServerHostname"), config.getParamValue("ServerPort"));
    }
}

END OF CLIENT CODE
BEGINNING OF SERVER CODE

public class Server {
    Server(String port){
        try(ServerSocket ss = new ServerSocket(Integer.parseInt(port))) {
            while(true) {
                Socket socket = ss.accept();
                ServerTask st = new ServerTask(socket, this);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String [] args) {
        Configuration config = new Configuration();
        config.configureFile();
        Server server = new Server(configuration.getPortNum());
    } 
}

0 个答案:

没有答案