用Python语言写一个socket通信代码
时间: 2024-03-28 11:15:42 浏览: 82
以下是一个简单的Python socket通信代码,实现了客户端和服务器之间的简单消息传递:
服务器端代码:
```python
import socket
# 创建一个TCP/IP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定服务器地址和端口号
server_address = ('localhost', 8888)
server_socket.bind(server_address)
# 开始监听连接请求
server_socket.listen(1)
print('Waiting for a connection...')
# 接受连接请求
client_socket, client_address = server_socket.accept()
print('Connection from', client_address)
# 接收客户端发送的消息
data = client_socket.recv(1024)
print('Received:', data.decode())
# 发送响应消息给客户端
message = 'Hello, client!'
client_socket.sendall(message.encode())
# 关闭连接
client_socket.close()
server_socket.close()
```
客户端代码:
```python
import socket
# 创建一个TCP/IP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器地址和端口号
server_address = ('localhost', 8888)
client_socket.connect(server_address)
# 发送消息给服务器
message = 'Hello, server!'
client_socket.sendall(message.encode())
# 接收服务器发送的响应消息
data = client_socket.recv(1024)
print('Received:', data.decode())
# 关闭连接
client_socket.close()
```
注意,这只是一个简单的示例代码,实际应用中需要考虑更多的异常处理、协议设计等方面。
阅读全文