我通过wifi通过TCP将数据从Android客户端发送到台式机服务器时遇到一些问题。该仿真器工作正常,但在实际的电话上,无法建立连接。抛出“套接字未连接”异常。
我在下面附加了我的代码。有什么帮助吗?非常感谢!
//活动内的代码
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.send:
sendMessage();
return true;
/// ...other items
}
}
private void sendMessage() {
String serverAddr = "18.xxx.xx.xxx";
Socket socket = null;
try {
socket = new Socket(serverAddr, 4444); // EXCEPTION HAPPENS HERE
} catch (Exception e) {
//show exception on screen
}
String message = "some message";
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
} catch (Exception e) {
//show exception on screen
} finally {
socket.close();
}
}
最佳答案
您的serverAddr不应为字符串,而应为InetAddr。
使用InetAddr.getByName(“ 18.x.x.x”)
关于android - Android:“套接字未连接”异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4201971/