编写一个 TCP服务器端SOCKET程序和TCP客户端SOCKET程序
时间: 2024-05-08 10:17:05 浏览: 166
TCP服务器端SOCKET程序:
```python
import socket
# 创建TCP服务器端socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind(('127.0.0.1', 8888))
# 监听客户端连接
server_socket.listen(5)
# 等待客户端连接
print('等待客户端连接...')
client_socket, client_address = server_socket.accept()
print('客户端已连接:', client_address)
# 接收客户端消息
while True:
data = client_socket.recv(1024)
if not data:
break
print('接收到客户端消息:', data.decode())
# 关闭连接
client_socket.close()
server_socket.close()
```
TCP客户端SOCKET程序:
```python
import socket
# 创建TCP客户端socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接
client_socket.connect(('127.0.0.1', 8888))
print('连接服务器成功!')
# 发送消息
client_socket.send('Hello, server!'.encode())
# 接收服务器消息
data = client_socket.recv(1024)
print('接收到服务器消息:', data.decode())
# 关闭连接
client_socket.close()
```
阅读全文