python如何创建一个tcp的客户端和服务端代码
时间: 2023-05-24 22:03:36 浏览: 122
A:
Python创建TCP客户端的代码:
```python
import socket
# 创建TCP客户端
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('localhost', 8888)
client_socket.connect(server_address)
# 发送消息
message = 'Hello, server!'
client_socket.sendall(message.encode())
# 接收响应并打印
response = client_socket.recv(1024).decode()
print('Received response:', response)
# 关闭socket连接
client_socket.close()
```
Python创建TCP服务端的代码:
```python
import socket
# 创建TCP服务器
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 开始监听连接
server_socket.listen()
print('Server listening on', server_address)
while True:
# 等待客户端连接
print('Waiting for client connection...')
client_socket, client_address = server_socket.accept()
print('Client connected from', client_address)
# 接收消息并打印
request = client_socket.recv(1024).decode()
print('Received request:', request)
# 处理消息并发送响应
response = 'Hello, client!'
client_socket.sendall(response.encode())
# 关闭客户端连接
client_socket.close()
```
以上代码为简单的示例代码,客户端和服务端的实际应用需要根据具体需求进行相应的调整和优化。
阅读全文