python实现tcp
时间: 2023-06-20 20:09:43 浏览: 49
以下是基于Python实现TCP的一些代码示例:
1. 服务器端代码示例:
```python
import socket
# 创建TCP Socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP和端口号
server_socket.bind(('localhost', 8888))
# 监听连接
server_socket.listen(1)
print('Waiting for client connection...')
while True:
# 接受客户端连接
client_socket, address = server_socket.accept()
print(f'Connected by {address}')
while True:
# 接收客户端数据
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
print(f'Received: {data}')
# 发送响应数据
response = f'Response: {data}'
client_socket.send(response.encode('utf-8'))
# 关闭客户端连接
client_socket.close()
```
2. 客户端代码示例:
```python
import socket
# 创建TCP Socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect(('localhost', 8888))
while True:
# 发送数据
data = input('Enter message to send: ')
client_socket.send(data.encode('utf-8'))
# 接收响应数据
response = client_socket.recv(1024).decode('utf-8')
print(response)
# 关闭连接
client_socket.close()
```
以上是Python实现TCP的简单示例,可以根据实际需求进行修改。