最近在做物联网项目,使用TCP传输数据可以用Python进行加简单的测试
import socket
def start_tcp_server(host, port):
# 创建TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_socket.bind((host, port))
# 监听连接
server_socket.listen(1)
print(f"Listening on {host}:{port}...")
while True:
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print(f"Connection from {client_address}")
# 接收数据
data = client_socket.recv(1024)
if not data:
break # 如果没有数据,跳出循环
# 显示接收到的数据
print(f"Received data: {data.decode('utf-8')}")
# 可以在这里添加处理接收到数据的逻辑
# 发送响应给客户端
response = "Message received successfully"
client_socket.send(response.encode('utf-8'))
# 关闭与客户端的连接
client_socket.close()
# 关闭服务器socket
server_socket.close()
if __name__ == "__main__":
# 指定服务器的主机和端口,使用0.0.0.0表示接受所有IP发起的连接
host = "0.0.0.0"
port = 777 # 使用一个未被占用的端口
start_tcp_server(host, port)
|