gsm*_*ker 5 java sockets connection android
我面临着从Android设备到PC的特定端口建立套接字连接的问题8080.我只想创建一个套接字,它将连接到特定端口,并在该端口上写入一些数据流.
我为此目的编写了一些代码,但代码给了我一个例外:
TCP Error:java.net.ConnectException:/127.0.0.1:8080-connection refused
Run Code Online (Sandbox Code Playgroud)
我给出的代码如下:
private static TextView txtSendStatus;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
String sentence = "TCP Test #1n";
String modifiedSentence;
try {
Socket clientSocket = new Socket("192.168.18.116", 8080);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
printScr("TCP Connected.");
outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFromServer.readLine();
printScr(modifiedSentence);
printScr("TCP Success !!!");
clientSocket.close();
} catch (Exception e) {
printScr("TCP Error: " + e.toString());
}
}
private void initControls()
{
txtSendStatus = (TextView)findViewById(R.id.txtSendStatus);
}
public static void printScr(String message)
{
txtSendStatus.append( "n" + message );
}
Run Code Online (Sandbox Code Playgroud)
有人能告诉我答案吗?我在等待正确的答案.
最诚挚的问候,gsmaker.
如果您使用的是wifi,则需要在wifi网络上使用PC的IP地址.您可以在命令行中使用ifconfig(linux)或ipconfig(windows)找到它
如果您使用的是usb adb连接,则无法完全执行此操作,但您可以设置从PC到手机的adb端口(请参阅开发人员文档),并让PC连接到它的环回接口和端口,它将被转发到应用程序应该监听的电话上的非特权端口号.然后,您可以使用TCP或任何可以向任一方向推送数据的连接.但PC必须是设置连接的发起者 - adb不支持"反向网络共享",其中手机以Android模拟器支持的方式启动与PC的网络连接.
您的服务器需要在设备上,客户端需要在计算机上.您需要让adb转发您要连接到设备的端口.建立连接后,您将能够正常地进行通信.
我在这里写了一个完整的解释http://qtcstation.com/2011/03/connecting-android-to-the-pc-over-usb/
首先,如果您尝试从您的设备连接到 127.0.0.1,那么您无法连接到 127.0.0.1 是合乎逻辑的。因为 127.0.0.1 是环回接口,并且始终指向设备本身。
因此,如果您从 PC 连接到 127.0.0.1,它会自行连接。如果你在 Android 上调用它,它也会尝试与自身连接。
其次:我认为唯一可以做到这一点的方法是当您使用 WLAN 时,只有这样您才能与 PC 建立基于 IP 的连接(如果我错了,请纠正我)。您无法使用 USB 或蓝牙连接到您的电脑。
| 归档时间: |
|
| 查看次数: |
20884 次 |
| 最近记录: |