# Python TCP通信示例代码
import socket
# 创建一个TCP/IP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定套接字到地址和端口
server_address = ('localhost', 10000)
print(f'Starting up on {server_address[0]} port {server_address[1]}')
server_socket.bind(server_address)
# 监听传入连接
server_socket.listen(1)
while True:
# 等待连接
print('Waiting for a connection...')
connection, client_address = server_socket.accept()
try:
print(f'Connection from {client_address}')
# 接收数据
while True:
data = connection.recv(16)
print(f'Received "{data.decode()}"')
if data:
# 发送数据回客户端
connection.sendall(data)
else:
print('No more data from', client_address)
break
finally:
# 清理连接
connection.close()
# 客户端代码
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
client_socket.connect(('localhost', 10000))
try:
message = 'This is the message. It will be repeated.'
print(f'Sending "{message}"')
client_socket.sendall(message.encode())
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = client_socket.recv(16)
amount_received += len(data)
print(f'Received "{data.decode()}"')
finally:
# 关闭连接
client_socket.close()
服务器端代码:
listen()方法监听传入的连接请求。accept()方法接受客户端的连接,返回一个新的套接字对象用于与客户端通信。客户端代码:
通过这个示例,你可以理解如何使用Python进行基本的TCP通信。
上一篇:python读取json并解析
下一篇:python如何写api接口
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站