且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过wifi将字符串从Android发送到PC

更新时间:2023-01-01 16:26:38

您必须在 PC 上编写一个服务器程序并使用 ServerSocket 来接受来自使用常规套接字的 Android 手机的连接并为其编写线程(与PC端的端口相同),然后使用DataInputStream和DataOutputStream对其进行管理.您还需要在 AndroidManifest.xml 上打开权限.

You would have to write a server program on the PC and use a ServerSocket to accept a connection from and write a thread for your Android phone that uses a regular socket (with the same port as the PC end) and then manage them using DataInputStream and DataOutputStream. You also need to open permissions on your AndroidManifest.xml.

对于权限使用这个:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

这里的代码是一个小例子:

For the code here's a little example:

服务器:

String msg_received;

ServerSocket socket = new ServerSocket(1755);
Socket clientSocket = socket.accept();       //This is blocking. It will wait.
DataInputStream DIS = new DataInputStream(clientSocket.getInputStream());
msg_received = DIS.readUTF();
clientSocket.close();
socket.close();

客户:

Socket socket = new Socket("192.168.0.1",1755);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("HELLO_WORLD");
socket.close();