开发者

Server Sockets Don't accept clients

开发者 https://www.devze.com 2023-04-12 15:48 出处:网络
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 sock开发者_开发百科et!

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 sock开发者_开发百科et!

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...


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号