用python写socket编程
时间: 2023-09-30 21:09:03 浏览: 90
详解Python Socket网络编程
好的,下面是一个使用 Python socket 编写的简单的客户端-服务器通信示例:
服务端代码:
```python
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
```
客户端代码:
```python
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
```
运行服务端代码后,它会在指定端口上监听连接请求。然后运行客户端代码,它将连接到服务端并发送一条消息。服务端将收到消息并将其回复给客户端,客户端将打印出收到的数据。
阅读全文