我正在嘗試android和windows之間的套接字通信。 一切工作正常,直到我使用10.0.2.2地址是模擬器運行的計算機的環回。但是,如果我給任何其他地址的Socket構造函數的連接超時。 我的目標是通過互聯網在我的手機和我的電腦之間進行通信。 我也試過在我的手機上,所以我不認爲這是防火牆問題。 這裏是我的代碼:通過互聯網的android套接字通信
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
clientSocket = new Socket("10.0.2.2", 48555);
Log.d("Offdroid", "socket connected");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.toString());
}
}
public void connectServer(View button) {
try {
String message = "shutdown";
byte[] messageBytes = message.getBytes("US-ASCII");
int messageByteCount = messageBytes.length;
byte[] messageSizeBytes = new byte[2];
messageSizeBytes = intToByteArray(messageByteCount);
byte[] sendBytes = concatenateArrays(messageSizeBytes, messageBytes);
Log.d("Offdroid", Integer.toString(messageSizeBytes.length));
clientSocket.setReceiveBufferSize(16);
clientSocket.setSendBufferSize(512);
OutputStream outStream = clientSocket.getOutputStream();
//InputStream inStream = clientSocket.getInputStream();
outStream.write(sendBytes, 0, sendBytes.length);
} catch(Exception EX) {
Log.e("Offdroid", EX.getMessage());
}
}
我也在尋找內置功能,而不是concatenateArrays功能,簡單地將兩個字節數組一起一個java。
編輯:
對不起,或許我沒有提供足夠的信息。我已經試過我的外部IP用於互聯網連接和我的局域網IP。路由器上的端口被轉發到我的電腦。所以,如果我寫「192.168.1.101」或互聯網服務提供商給出的IP代替「10.0.2.2」,比我無法連接。
編輯:
好吧,我知道這是我的防火牆。
對不起,也許我沒有提供足夠的信息。 我已經試過我的外部IP用於互聯網連接和我的局域網IP。路由器上的端口被轉發到我的電腦。 因此,如果我寫「192.168.1.101」或由互聯網服務提供商給出的IP地址代替「10.0.2.2」,比我無法連接。 – Jumi