0
我有一個關於通過TCP/IP在兩個android設備之間的消息傳遞的問題。問題是我無法發送任何消息到第二個Android設備。當我輸入第一個設備的本地IP時,我可以向自己發送消息。這裏是我的服務器和客戶端類:Android的TCP/IP連接
服務器類:
公共類ServerThread實現Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
@Override
public void run() {
//serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(8080);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
//serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
final String a=line.toString();
Log.d("ServerActivity", line);
handler.post(new Runnable() {
@Override
public void run() {
thelist.add(a);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.chat_view, R.id.chat_view_label, thelist);
lvMessage.setAdapter(arrayAdapter);
//onStop();
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
//serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
@Override
public void run() {
//serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
//serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
Client類:
公共類ClientThread實現Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("141.196.41.145");
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr,8080);
//Socket socket = new Socket("141.196.41.145",8080);
connected=true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
// where you issue the commands
out.println(" MT 02 : " + thevariable);
Log.d("ClientActivity", "C: Sent.");
break;
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected=false;
}
}
}
有「141.196.41.145」是本地IP o我的第二個設備。如果我將此IP更改爲我的第一個設備的本地IP,我可以向自己發送消息。
感謝您的關注和幫助
你有2個模擬器檢查? –
不,我正在使用兩個android設備 – user2982112