用python写两个socket通信函数,一个接收一个发送
时间: 2023-03-22 07:01:19 浏览: 64
好的,我理解您的问题并将尽力回答。
以下是用Python编写两个Socket通信函数的示例代码,一个用于接收消息,一个用于发送消息:
```python
import socket
def receive_message(host, port):
# 创建socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP和端口号
sock.bind((host, port))
# 监听连接
sock.listen()
# 接受连接并接收消息
conn, addr = sock.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print(data.decode())
def send_message(host, port, message):
# 创建socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
sock.connect((host, port))
# 发送消息
sock.sendall(message.encode())
# 关闭连接
sock.close()
```
使用这些函数时,您需要将`host`和`port`参数替换为相应的主机名和端口号,并根据需要在发送消息时提供`message`参数。例如,要接收来自主机`localhost`,端口`8000`的消息,可以调用`receive_message("localhost", 8000)`。要将消息`"Hello, world!"`发送到主机`localhost`,端口`8000`,可以调用`send_message("localhost", 8000, "Hello, world!")`。