当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Unable to open a socket server

问题描述:

I am trying to make a simple client and server connection. However the server does not seem to bind to the port appropriately.

The code I am using for the server is written below:

class Server extends Thread

{

public boolean running = true;

public Server(Main main) throws IOException

{

super();

ServerSocket server_sock = new ServerSocket(8123);

while (running)

{

new Connector(server_sock.accept(), main);

}

server_sock.close();

}

}

class Connector extends Thread

{

public Connector(Socket c)

{

super();

system.out.println("Connecting"+c.getRemoteSocketAddress()+":"+c.getLocalPort());

c.setKeepAlive(true);

//wait for the connection to end

system.out.println("Disconnecting"+c.getRemoteSocketAddress()+":"+c.getLocalPort());

}

}

The client is rather simple, I just want to connect to the server (The lines shown below is run via another program in its main):

s = new Socket("127.0.0.1", 8123); // Start

s.close(); // Stop

What happens: the server runs and does not throw any exceptions. Hopeful I ran the client where it threw an exception Exception in thread "main" java.net.ConnectException: Connection refused: connect.

So I made a simple python client & server pair to check the Java server / clients:

Server:

from socket import *

s = socket(AF_INET, SOCK_STREAM)

s.bind(('', 8123))

s.listen(1)

conn, addr = s.accept()

print("CONNECTED: ", addr)

conn.close()

Client:

from socket import *

s = socket(AF_INET, SOCK_STREAM)

s.connect(('localhost', 8123))

s.close()

I tested python server with python client as a sanity test, which worked just fine. I tested the python server with the java client and they both cooperated just fine. However, python client and java series does not work. My python server provides the error:

Traceback (most recent call last):

File "C:\Users\SIGABRT\Desktop\tcp.py", line 4, in <module>

s.connect(('localhost', 8123))

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

Which typically means that the server is not started properly. So what am I doing wrong with the Java server client?

网友答案:

I have the same issue. For me, it helps to do

s = new Socket("localhost", 8123);

I wonder why it doesn't work with the IP...

Explanation

At least on my Ubuntu system, it seems like new ServerSocket(port) sets up a connection with IPv6 - "127.0.0.1" is IPv4 and cannot connect to the socket being set up. The alternative is to initialize the server socket with

new ServerSocket(port, 32, Inet4Address.getByName("127.0.0.1"));

I don't know if using IPv4 over IPv6 makes a real difference (performance-wise) when used via loopback address.

分享给朋友:
您可能感兴趣的文章:
随机阅读: