tcp c/s demo
时间: 2023-07-28 07:17:46 浏览: 39
这是一个简单的TCP客户端/服务器端示例。该程序使用Python的socket库实现。
服务器端代码:
```python
import socket
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind(('localhost', 8000))
# 等待客户端连接
server_socket.listen(1)
print('服务器已启动,等待客户端连接...')
# 等待客户端连接请求
client_socket, client_address = server_socket.accept()
print('客户端已连接:', client_address)
# 发送数据
client_socket.send('欢迎连接到服务器!'.encode())
# 接收客户端发送的数据
data = client_socket.recv(1024)
print('客户端发来的数据:', data.decode())
# 关闭连接
client_socket.close()
server_socket.close()
```
客户端代码:
```python
import socket
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect(('localhost', 8000))
# 接收服务器发送的数据
data = client_socket.recv(1024)
print('服务器发来的数据:', data.decode())
# 发送数据
client_socket.send('你好,服务器!'.encode())
# 关闭连接
client_socket.close()
```
在本地运行服务器端代码后,再运行客户端代码即可进行通信。注意,服务器端必须先启动,客户端才能连接上。