为什么我不能通过套接字收听127.0.0.1:port

时间:2019-09-19 15:11:34

标签: java macos sockets

java.net.ConnectException:连接被拒绝(连接被拒绝)

没有使用端口的程序

Socket socket = new Socket("127.0.0.1", 9876);
java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)

1 个答案:

答案 0 :(得分:1)

您创建客户端套接字。因此,某些服务器应侦听9876端口,否则您将获得java.net.ConnectException: Connection refused (Connection refused)。如果您想听9876,请使用:

服务器:

ServerSocket serverSocket = new ServerSocket(9876);
Socket socket = server.accept(); // accept() waiting for client connection
//read from socket on server
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Message from client " + in.readLine());   

之后,您可以创建一个客户端:

位置:

Socket clientSocket = new Socket("localhost", 9876);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
out.write("Hello! " + "\n"); // send to server
out.flush();