Android设备到PC的套接字连接

我面临着从Android设备到PC的特定端口(如8080建立套接字连接的问题。 我只想创建一个套接字,它将连接到特定端口,并在该端口上写入一些数据流。

我为此目的编写了一些代码,但代码给了我一个例外:

 TCP Error:java.net.ConnectException:/127.0.0.1:8080-connection refused 

我给出的代码如下:

 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 ); } 

有人能告诉我答案吗? 我在等待正确的答案。

最诚挚的问候,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是环回接口并始终指向设备本身。

因此,如果从PC连接到127.0.0.1,它将自行连接。 如果你在android上调用它,它也试图与自己连接。

第二:我认为你能做到这一点的唯一方法是当你使用WLAN时,只有你有基于IP的PC连接(如果我错了,请纠正我)。 您无法使用USB或蓝牙连接到PC。