0
我在這裏有一些代碼連接到服務器,我收到錯誤java.net.ConnectException:連接拒絕。拒絕Java TCP套接字連接
我嘗試在命令行上使用ping
,我收到了數據包,所以我知道它正在工作。
我也嘗試使用telnet
連接到我的IP地址,它給了我同樣的連接拒絕錯誤。我的代碼有問題嗎?我不確定爲什麼我的連接被拒絕。
客戶:
public class InstantMessagingClient
{
private Socket socket;
public InstantMessagingClient(String serverName, int port)
{
new Thread() {
public void run()
{
try
{
System.out.println("Connecting to " + serverName + " and port: " + port);
//socket.setSoTimeout(10000);
socket = new Socket(serverName, port);
System.out.println("Client: connected to server at address: " + socket.getLocalAddress() + " and port: " + socket.getPort());
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}.start();
}
}
服務器:
public class InstantMessagingServer
{
private int port;
private Socket clientSocket;
private ServerSocket serverSocket;
public InstantMessagingServer(int port)
{
try
{
this.port = port;
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
System.out.println("Server: Connected to port");
new Thread()
{
public void run()
{
while(true)
{
try
{
System.out.println("Server: Waiting for port " + serverSocket.getLocalPort());
System.out.println(serverSocket.getLocalSocketAddress());
clientSocket = serverSocket.accept();
System.out.println("Server: Just connected to " + clientSocket.getRemoteSocketAddress());
}
catch(Exception e)
{
System.out.println(e.toString());
break;
}
}
}
}.start();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
主營:
public void main()
{
InstantMessagingServer server = new InstantMessagingServer(18638);
InstantMessagingClient client = new InstantMessagingClient("(My IP Address)", 18638);
}