我正在尝试使用套接字设置受保护的客户端和受保护的服务器连接。每当我运行程序时,我收到连接错误,说连接被拒绝。我在运行在MAC OS上的Eclipse IDE中使用Java。有什么想法为什么这段代码无法连接到我的localhost?
受保护的客户端:
public static void main(String[] args) throws Exception
{
String host = "localhost";
int port = 7999;
String user = "George";
String password = "abc123";
Socket s = new Socket(host, port);
ProtectedClient client = new ProtectedClient();
client.sendAuthentication(user, password, s.getOutputStream());
s.close();
}
受保护的服务器
public static void main(String[] args) throws Exception
{
int port = 7999; //7999
ServerSocket s = new ServerSocket(port);
Socket client = s.accept();
ProtectedServer server = new ProtectedServer();
if (server.authenticate(client.getInputStream()))
System.out.println("Client logged in.");
else
System.out.println("Client failed to log in.");
s.close();
}
当我运行程序时,我收到以下错误:
Exception in thread "main" java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:431)
at java.net.Socket.connect(Socket.java:527)
at java.net.Socket.connect(Socket.java:476)
at java.net.Socket.<init>(Socket.java:373)
at java.net.Socket.<init>(Socket.java:216)
at ProtectedClient.main(ProtectedClient.java:36)
答案 0 :(得分:0)
我在使用特定套接字之前遇到此错误。尝试使用不同的套接字,如5687.(或者,如果您需要特定的套接字,请尝试确保您的防火墙允许它。)
确保您也在服务器上调用client.close()。 如果您的程序有效,可能会阻止该端口。