用python实现socket通信
时间: 2023-09-19 21:10:14 浏览: 95
python实现Socket通信
以下是一个简单的 Python Socket 通信例子:
服务端代码(server.py):
```
import socket
# 创建一个 TCP/IP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定 socket 到本地IP与端口
server_address = ('localhost', 9999)
print('Starting up on %s port %s' % server_address)
server_socket.bind(server_address)
# 开始监听进来的连接
server_socket.listen(1)
while True:
# 等待一个新连接
print('Waiting for a connection...')
client_socket, client_address = server_socket.accept()
print('Connection from', client_address)
# 收到消息并发送回去
while True:
data = client_socket.recv(1024)
print('Received:', data.decode())
if data:
client_socket.sendall(data)
else:
print('No more data from', client_address)
break
# 清理连接
client_socket.close()
```
客户端代码(client.py):
```
import socket
# 创建一个 TCP/IP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务端的地址和端口号
server_address = ('localhost', 9999)
print('Connecting to %s port %s' % server_address)
client_socket.connect(server_address)
# 发送消息
message = 'Hello, world!'
client_socket.sendall(message.encode())
# 接收服务端返回的消息
data = client_socket.recv(1024)
print('Received:', data.decode())
# 关闭连接
client_socket.close()
```
运行 server.py 启动服务端,然后运行 client.py 启动客户端,就可以在客户端和服务端之间进行通信了。
阅读全文