linux+python实现tcp
时间: 2023-10-10 17:08:01 浏览: 73
下面是一个基本的Python TCP服务器和客户端示例:
服务器端:
```python
import socket
# 创建TCP socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定服务器地址和端口
server_socket.bind(('localhost', 8888))
# 监听连接
server_socket.listen()
print('Server is listening on port 8888...')
while True:
# 接受连接请求
client_socket, address = server_socket.accept()
print(f'New connection from {address}')
# 接受客户端发送的消息
message = client_socket.recv(1024)
print(f'Received message from client: {message.decode()}')
# 发送响应消息给客户端
response = 'Hello from server!'
client_socket.send(response.encode())
# 关闭连接
client_socket.close()
```
客户端:
```python
import socket
# 创建TCP socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect(('localhost', 8888))
# 发送消息给服务器
message = 'Hello from client!'
client_socket.send(message.encode())
# 接受服务器发送的响应消息
response = client_socket.recv(1024)
print(f'Received message from server: {response.decode()}')
# 关闭连接
client_socket.close()
```
阅读全文