有鑑於此:設置插座的本地端口拋出異常
. . .
ServerSocket serverSocket = new ServerSocket(1111);
while (helperSockets.size() < Common.NUM_HELPERS) {
Socket helperSocket = serverSocket.accept();
. . .
這引發異常:
new Socket("localhost", 1111, InetAddress.getLocalHost(), localPort);
例外:
java.net.ConnectException: connect: Address is invalid on local machine, or port is not valid on remote machine
我試圖用這個構造函數來設置當地的港口,所以我做錯了什麼?來源如下。
構造函數創建一個線程,該線程通過ServerSockets偵聽客戶端,同時嘗試連接到其他客戶端。該客戶端嘗試與自己進行連接以進行測試。在for循環的第一次迭代中會遇到問題。
public class DisSemHelper extends Thread {
private int id;
private int semaphore;
private Clock clock;
private Vector<Socket> helperSockets;
private int localPort;
private int receivedSender;
private String receivedOperation;
private int receivedTimestamp;
/**
*/
public DisSemHelper(int id) {
this.id = id;
this.semaphore = 0;
this.clock = new Clock();
this.helperSockets = new Vector<Socket>();
this.receivedSender = -1;
this.receivedOperation = null;
this.receivedTimestamp = -1;
this.localPort = Common.portMap.get(id);
new ConnectionListener().start();
/* Create and store connections to all helpers */
for (int i=0; helperSockets.size() < Common.NUM_HELPERS; i++) {
Socket helperSocket = null;
// String portKey = "STREET_" + i;
/* Wait until target street socket is ready. Retry every second. */
Exception e = new ConnectException();
while (helperSocket == null) {
try {
Thread.sleep(1000);
helperSocket = new Socket("localhost", 2222, InetAddress.getLocalHost(), localPort);
} catch (ConnectException ce) {
e = ce;
e.printStackTrace();
} catch (UnknownHostException uhe) {
uhe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
e.printStackTrace();
}
}
int remotePort = helperSocket.getPort();
int connectedHelperID = Common.portMap.indexOf(remotePort);
if (this.helperSockets.size() <= connectedHelperID) {
this.helperSockets.add(helperSocket);
System.out.println("Helper " + id + " added socket from outgoing: local port: " + helperSocket.getLocalPort() + " remote port: " + helperSocket.getPort());
}
}
System.out.println(this.helperSockets);
}
private class ConnectionListener extends Thread {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(2222);
/* Listen for connections from other helpers */
while (helperSockets.size() < Common.NUM_HELPERS) {
Socket helperSocket = serverSocket.accept();
// TODO Will indexof int in list of Integers work?
int remotePort = helperSocket.getPort();
int connectedHelperID = Common.portMap.indexOf(remotePort);
// TODO Does this really work?
if (connectedHelperID == -1) {
helperSockets.add(helperSocket);
System.out.println("Helper " + id + " added socket from incoming: local port: " + helperSocket.getLocalPort() + " remote port: " + helperSocket.getPort());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
是我的壞。上面的問題中添加了異常。忘記打印堆棧跟蹤。 – Rooster
是的,那個實際上工作。但我仍然需要設置本地端口。 – Rooster
不確定你設置本地端口的意思。對不起,我不能更有幫助。 \ –