我設計一個所有到所有Android程序,包括5個節點:設置S/C之間的TCP連接中的Android /爪哇
- 每個節點充當服務器和客戶端
- 每個節點將連接到其他4個節點。
- 每個節點將監聽並接受其他4個節點的連接。
雖然我的問題是,如果5個節點以1-2-3-4-5的順序啓動,Node1的tcp連接請求將不會被Node2接受,因爲Node2稍後啓動爲了解決這個問題,我試過使用isConnected()
,但是即使只有Node1啓動,它總是會返回true
。爲了解決這個問題,我試過使用isConnected()
,但是它總是返回true
。
所以我的問題是如何在3個Android節點之間建立一個全部到所有的TCP連接。
附件是我的代碼:
private class ClientTask extends Thread {
Socket[] s1 = new Socket[5];
@Override
public void run() {
int flag=1;
for (int i = 0; i < 5; i++) {
if(flag==0) i--;
try {
System.out.println("Begin making connections!");
//s1[i] = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),REMOTE_PORT[i]);
s1[i] = new Socket();
s1[i].connect(new InetSocketAddress("10.0.2.2", REMOTE_PORT[i]),1000);
flag=1;
} catch (UnknownHostException e) {
System.out.println("ClientTask UnknownHostException");
flag=0;
} catch (IOException e) {
//Error happens when set_redir.py is not run
System.out.println("ClientTask socket IOException");
flag=0;
}
}
}
}
而對於服務器的代碼:
public class ServerTask extends Thread {
ServerSocket serverSocket = null;
public void run() {
System.out.println("Start listening!");
Socket socket = null;
try {
serverSocket = new ServerSocket(10000);
} catch (IOException e) {
System.out.println("Error when creating serversocket!");
}
int flag=1;
for (int i = 0; i < 5; i++) {
if(flag==0) i--;
try {
// waiting for incoming socket
socket = serverSocket.accept();
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
try{
out.writeBytes("You are connected to avd: " + (myPort-11108)/4);
}catch (IOException e){
System.out.println("Error here!");
}
flag=1;
// new thread for the full TCP connection
System.out.println("Receiving new TCP connection from " + socket.getRemoteSocketAddress());
tt[i] = new tcpThread(socket, i);
tt[i].start();
} catch (IOException e) {
System.out.println("ERROR: server socket");
flag=0;
}
}
System.out.println("End listening...");
}
}
'S/C'是什麼?短路? – EJP
@EJP服務器/客戶端... – newbieSOF
那麼爲什麼不這樣說呢?一切都不是TLA。可能是任何事情。 – EJP