给我写一段socket通信的例子
时间: 2023-08-12 12:33:29 浏览: 81
好的,下面是一个简单的Python Socket通信的例子:
服务端代码:
```python
import socket
# 创建一个TCP/IP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定本地地址和端口
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 开始监听
server_socket.listen(1)
# 循环等待客户端连接
while True:
print('等待客户端连接...')
client_socket, client_address = server_socket.accept()
try:
print('客户端已连接:', client_address)
# 接收客户端发送的消息
while True:
data = client_socket.recv(1024)
print('接收到消息:', data.decode())
if data:
# 发送消息给客户端
client_socket.sendall(data)
else:
# 没有数据,退出循环
break
except Exception as e:
print('发生异常:', e)
finally:
# 关闭客户端连接
client_socket.close()
```
客户端代码:
```python
import socket
# 创建一个TCP/IP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务端
server_address = ('localhost', 8888)
client_socket.connect(server_address)
try:
# 发送消息给服务端
message = 'Hello, World!'
client_socket.sendall(message.encode())
# 接收服务端发送的消息
data = client_socket.recv(1024)
print('收到服务端的回复:', data.decode())
finally:
# 关闭套接字
client_socket.close()
```
运行服务端程序后,再运行客户端程序,你就可以看到客户端发送的消息被服务端接收并回复了。
阅读全文