views:

180

answers:

1

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());
+2  A: 

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.

Ash
Thanks, I see what you mean. I've run it in a different thread and it works.
Dois