python客户端服务端
时间: 2023-10-03 16:07:36 浏览: 91
Python中的客户端和服务器端可以使用socket模块进行实现。你可以使用socket模块创建Socket对象,然后使用该对象进行网络通信。
服务器端代码示例:
```python
import socket
# 创建一个服务器Socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 监听连接
server_socket.listen(1)
print('Server is listening on {}:{}'.format(*server_address))
while True:
# 等待客户端连接
client_socket, client_address = server_socket.accept()
try:
print('Client connected:', client_address)
# 接收客户端发送的数据
data = client_socket.recv(1024)
if data:
print('Received data:', data.decode())
# 向客户端发送响应数据
response = 'Hello from server!'
client_socket.sendall(response.encode())
finally:
# 关闭客户端连接
client_socket.close()
```
客户端代码示例:
```python
import socket
# 创建一个客户端Socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('localhost', 8888)
client_socket.connect(server_address)
try:
# 向服务器发送数据
message = 'Hello from client!'
client_socket.sendall(message.encode())
# 接收服务器响应
data = client_socket.recv(1024)
print('Received response:', data.decode())
finally:
# 关闭客户端连接
client_socket.close()
```
运行服务器端代码后,再运行客户端代码,你将看到服务器端打印出客户端连接信息,并向客户端发送响应数据。客户端接收到响应数据后打印出来。这样就完成了基本的Python客户端和服务器端的通信。
阅读全文