2012-02-02 34 views
0

我使用TCPsocket來通信客戶端和服務器。Android:在兩個系統之間發送/接收數據

客戶端代碼:

InetAddress inet = InetAddress.getByName("localhost"); 
int TCP_SERVER_PORT = 21111; 
Socket s = new Socket(inet, TCP_SERVER_PORT); 
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); 
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 
String outMsg = "connect" + TCP_SERVER_PORT+System.getProperty("line.separator"); 
out.write(outMsg); 
out.flush(); 
Log.i("TcpClient", "Client sent - : " + outMsg); 
String inMsg = in.readLine() + System.getProperty("line.separator"); 
textReceived.append("Client received - : " + inMsg); 
Log.i("TcpClient", "Client received - : " + inMsg); 
s.close(); 

Server代碼:

ServerSocket ss = null; 
int TCP_SERVER_PORT = 21111; 
ss = new ServerSocket(TCP_SERVER_PORT); 
Socket s = ss.accept(); 
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); 
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); 
String incomingMsg = in.readLine() + System.getProperty("line.separator"); 
Log.i("TcpServer", "received: " + incomingMsg); 
textDisplay.append("Server received - : " + incomingMsg); 
String outgoingMsg = "Port " + TCP_SERVER_PORT + System.getProperty("line.separator"); 
out.write(outgoingMsg); 
out.flush(); 
Log.i("TcpServer", "sent: " + outgoingMsg); 
textDisplay.append("Server sent - : " + outgoingMsg); 
s.close(); 

我用單一的模擬器在我的系統,以測試這個程序。它的工作正常。 現在我需要與兩臺電腦溝通。

+0

當你說兩臺電腦時,你的意思是你需要在模擬器的兩個實例之間測試這種運行嗎? – mcnicholls 2012-02-02 13:49:25

+0

兩個模擬器與不同的計算機 – Kamal 2012-02-02 13:54:02

回答

0

由於每個仿真器實例位於虛擬防火牆之後,因此您需要允許主機上的端口重定向到您的仿真器實例。

This頁面詳細介紹瞭如何通過telnet連接到模擬器實例並啓用端口重定向。

如果您在每臺計算機上運行仿真器,然後設置端口重定向,則應該能夠通過指定主機的IP和端口來從另一臺仿真器實例到另一臺仿真器實例。當你有一個重定向的地方,你的主機應該選擇它並將其重定向到模擬器實例。

相關問題