Programme goes unresponsive at ServerSocket.accept - Java

依然范特西╮ 提交于 2019-12-11 08:34:58

问题


My programme listens for just one connection once... the programme just gets stuck at clientSocket = serverSocket.accept() if no client connects. I mean I can't even interrupt it by closing my window. I can't click any of my buttons in the frame etc.

I've used this code the same way in my other programmes but it's worked fine (I can click text fields and buttons and stuff and type values in them, for this one, it just freezes there until a client connects, can't even exit).

public void runServer() {
    try {
        serverSocket = new ServerSocket(PORT_NUMBER, 20);
        clientSocket = serverSocket.accept();
        taDisplay.append("Client connected!");
        lblPlayingTo.setText("Playing to: " + objective);

        socketIn = new DataInputStream(clientSocket.getInputStream());
        socketOut = new DataOutputStream(clientSocket.getOutputStream());

        socketOut.writeUTF(serverName);
        clientName = socketIn.readUTF();
        lblEastScore.setText(clientName + ": " + eastScore.getScore());  

    } catch (IOException e) {
        System.out.println(e);
        taDisplay.append("Could not listen on port: " + PORT_NUMBER + ".\n");
    }
}

I've removed all my code except this (below) but I still get the same 'freezing' problem

    setTitle(title);
    setSize(sizeW, sizeH);
    setVisible(visibility);
    setResizable(resizability);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addKeyListener(new MyKeyAdapter());
    addMouseListener(new MyMouseAdapter());

    //Container
    c = getContentPane();
    c.setLayout(new BorderLayout());

回答1:


It sounds like you're doing your serverSocket.accept() call on the GUI's Event Dispatch Thread (EDT). Swing relies on the EDT for rendering and handling user interaction - if you do a blocking call like "accept", you won't see any updates on the GUI.

What you'll need to do is create a new thread (or use the application's "main" thread, which is different to the EDT) that sits on the accept waiting for the client to connect. After the connection it can do any of the work it needs to, but when you want to update the GUI, you need to wrap the code to do the update in a Runnable and pass it to the EDT via SwingUtilities.invokeLater.



来源:https://stackoverflow.com/questions/2170551/programme-goes-unresponsive-at-serversocket-accept-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!