Python socket实例代码
时间: 2024-08-02 16:00:43 浏览: 67
在Python中,socket模块用于创建网络套接字,实现客户端和服务器之间的通信。这里是一个简单的TCP服务器和客户端的例子:
**服务器端(server.py)**:
```python
import socket
# 创建一个socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机名或IP地址
host = 'localhost'
port = 9999
# 绑定端口
server_socket.bind((host, port))
# 设置最大连接数
server_socket.listen(5)
while True:
# 建立新连接
client_socket, addr = server_socket.accept()
print(f"Accepted connection from {addr}:{addr}")
# 接收数据
request = client_socket.recv(1024)
print(f"Received: {request.decode()}")
# 回应数据
response = "Hello from the server!"
client_socket.send(response.encode())
# 关闭连接
client_socket.close()
```
**客户端(client.py)**:
```python
import socket
# 创建一个socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到服务器
host = 'localhost'
port = 9999
client_socket.connect((host, port))
# 发送数据
message = "Hello, Server!"
client_socket.send(message.encode())
print("Sent:", message)
# 接收响应
response = client_socket.recv(1024)
print("Received:", response.decode())
# 关闭连接
client_socket.close()
```
运行`server.py`作为服务端启动监听,然后运行`client.py`作为客户端进行连接。
阅读全文