tcp server和client代码示例
时间: 2023-08-28 18:12:01 浏览: 81
下面是一个简单的TCP服务器和客户端的代码示例(使用Python的socket模块):
TCP Server:
```python
import socket
# 创建TCP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP和端口号
server_socket.bind(('localhost', 8000))
# 监听连接
server_socket.listen(1)
print('Server started, waiting for connection...')
# 接受连接请求
client_socket, addr = server_socket.accept()
print(f'Connected by {addr}')
# 接收数据
data = client_socket.recv(1024)
print(f'Received data: {data.decode()}')
# 发送数据
client_socket.sendall('Hello, client!'.encode())
# 关闭连接
client_socket.close()
# 关闭服务器套接字
server_socket.close()
```
TCP Client:
```python
import socket
# 创建TCP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect(('localhost', 8000))
# 发送数据
client_socket.sendall('Hello, server!'.encode())
# 接收数据
data = client_socket.recv(1024)
print(f'Received data: {data.decode()}')
# 关闭连接
client_socket.close()
```
注意:以上代码示例仅供参考,实际应用中需要根据需求进行修改和完善。
阅读全文