How to transfer data in real time between mobile phone and computer

To transmit data in real time between mobile phone and computer, you can use Socket for communication.

The following is a simple sample code that uses the mobile phone as the client and the computer as the server to transmit data between them through Socket.

Server side (computer):

import socket

# 创建一个Socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 获取本机主机名和端口号
host = socket.gethostname()
port = 8888

# 绑定主机名和端口号
server_socket.bind((host, port))

# 开始监听客户端连接
server_socket.listen(1)

# 等待客户端连接
print('等待客户端连接...')
client_socket, addr = server_socket.accept()

# 循环接收客户端发送的数据
while True:
    data = client_socket.recv(1024)
    if not data:
        break

    # 打印接收到的数据
    print('收到客户端发送的数据:', data.decode())

    # 向客户端发送数据
    msg = '已收到数据:' + data.decode()
    client_socket.send(msg.encode())

# 关闭客户端连接和服务器Socket
client_socket.close()
server_socket.close()

Client (mobile phone):

import socket

# 创建一个Socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 获取服务器主机名和端口号
host = '服务器IP地址'
port = 8888

# 连接服务器
client_socket.connect((host, port))

# 循环发送数据给服务器
while True:
    msg = input('请输入要发送的数据:')
    client_socket.send(msg.encode())

    # 接收服务器发送的数据
    data = client_socket.recv(1024)
    print('收到服务器发送的数据:', data.decode())

# 关闭Socket连接
client_socket.close()

Method to realize:

The server creates a Socket object, binds the local host name and port number, and then starts listening for client connections.

After the client connects successfully, the server receives the data from the client and sends the received data back to the client. After the client successfully connects to the server, it can send data to the server in a loop and wait for the server's reply.

Guess you like

Origin blog.csdn.net/KingOfOnePiece/article/details/131866050