Thiago Moraes
Thiago Moraes

Reputation: 617

Socket works on command line but fails on Swing

This question is a follow-up to this one: BufferedReader readLine method hangs and block program

I have now a server and a client that runs smoothly, but then I tried to implement a GUI interface using swing. Using the same code, the socket constructor fails.

My class is like this:

public class TCPClient {

    public BufferedWriter ostream = null;
    public BufferedReader istream = null;
    public TCPClient(String host, String port) throws UnknownHostException {
    InetAddress ip = InetAddress.getByName(host);

    try {
        Socket socket = new Socket(host, Integer.parseInt(port));

        ostream = new BufferedWriter(socket.getOutputStream());
        istream = new BufferedReader(new InputStreamReader(socket.getInputStream()));


    } catch (IOException ex) {
        Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
    }

}

This code works perfectly when calling from a main function. In swing, I have a button that calls the following method:

private void enviarMsgTCP() throws IOException {
    screenOutput.append("Sent:\n" + mensagem.getText() + "\n");
    if (client == null){
        try {
            client = new TCPClient(destIp.getText(), port.getText());
        } catch (UnknownHostException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
            saidaTexto.append("Não foi possível se conectar ao host.\n");
        }
    }

Using this code, the line below (in TCPClient) throws an exception:

Socket socket = new Socket(host, Integer.parseInt(port));

The exception stacktrace:

21/10/2011 21:44:42 cliente.ClienteTCP <init>
GRAVE: null
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:218)

What can it be? thx again

Upvotes: 2

Views: 223

Answers (1)

user207421
user207421

Reputation: 310909

Connection refused means nothing is listening at the IP:port you specified when connecting.

How come you still have the DataOutputStream?

Upvotes: 2

Related Questions