0
votes

I'm learning about sockets in java. I was able to connect a client socket to an online server, but I can connect them to my own server socket!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

class Blargh2 {
    public static void main(String[] args) {
        Socket client = null;
        ServerSocket server = null;
        System.out.println("Line one reacehd!");
        try {
            server = new ServerSocket(4445);
        } catch (Exception e) {
            System.out.println("Error:" + e.getMessage());
        }
        System.out.println("Line two reacehd!");
        try {
            client = server.accept();
        } catch (IOException e) {
            System.out.println("Accept failed: 4444");
            System.exit(-1);
        }

        System.out.println("Line three reacehd!");
        try {
            server.close();
            client.close();
        } catch (IOException e) {
            System.out.println("Accept failed: 4444");
            System.exit(-1);
        }
    }
}

The program reaches lines one and two but it never reaches line 3! Can anyone help me solve this? Firewall also allows this connection...

2
Are you beware of the fact that your ServerSocket is running on port 4445?Martijn Courteaux
How are you connecting in to your server? telnet?Paul Cager
How am I supposed to connect? OK this is the first time I'm doing sockets. I thought that the only thing I have to do is to create the server, and then connect the socket by using the accept() method.dsynkd

2 Answers

3
votes

It never reaches line 3 because you need a remote TCP socket (although it can be local, for testing) to connect to your socket on port 4445. You accept endpoint sockets on the server, which are used for communication with the remote client. There is actually no client here, so it waits indefinitely or until a timeout on the accept() call.

0
votes

Try running this code and after you see line 2 is executed, then run the windows command:

telnet localhost 4445

Then you should see your line 3 executed.