Python中如何编写一个简单的服务器程序
发布时间:2023-12-28 02:17:00
编写一个简单的服务器程序可以使用Python的socket库来实现。以下是一个使用TCP协议的例子。
import socket
def handle_client(connection):
request = connection.recv(1024) # 接收客户端请求
response = "Hello, client!" # 应答消息
connection.sendall(response.encode()) # 发送应答消息
connection.close() # 关闭连接
def run_server():
host = '' # 监听所有网络接口
port = 8080 # 监听端口
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建套接字
server_socket.bind((host, port)) # 绑定地址和端口
server_socket.listen(5) # 监听客户端连接
print("Server is running on port %d" % port)
while True:
conn, addr = server_socket.accept() # 接受客户端连接
print("Connected by", addr)
handle_client(conn) # 处理客户端请求
if __name__ == "__main__":
run_server()
这个服务器程序通过监听指定的端口,接受客户端的连接请求,并对客户端的请求进行处理。在此例中,服务器接收到客户端连接后,发送一个Hello, client!的应答消息给客户端。
要运行服务器程序,可以在终端中运行该脚本,并使用浏览器或其他网络工具访问localhost:8080。你将看到服务器端输出Connected by和客户端输出Hello, client!的结果。
这只是一个简单的例子,实际上,服务器程序可以根据需求进行更复杂的处理,比如返回动态内容、接收表单提交等。
