提问人:Gomenburu 提问时间:6/29/2022 更新时间:6/29/2022 访问量:114
如何永久运行 python 服务器端代码?
How would I permanently run python server-side code?
问:
我正在使用一个需要一些服务器端代码的教程,但它们没有显示如何永久运行它。有什么方法可以做到这一点,也许是使用 Web 服务器?代码如下:
import socket, threading
host = '127.0.0.1'
port = 7976
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} left!'.format(nickname).encode('ascii'))
nicknames.remove(nickname)
break
def receive():
while True:
client, address = server.accept()
print("Connected with {}".format(str(address)))
client.send('NICKNAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print("Nickname is {}".format(nickname))
broadcast("{} joined!".format(nickname).encode('ascii'))
client.send('Connected to server!'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
答: 暂无答案
评论