我想编写一个可以根据客户端输入停止服务器的应用程序。服务器是多线程的,我不明白我该怎么做。
基本上,我在这里描述了我的问题:Modify server's variable from client's thread (threading, python)。
然而,这是Python解决方案,而不是我可以在Java,C,C ++等中实现的通用解决方案。
我需要关闭其他客户端,当其中一个猜测数字时,服务器应该还活着,为新游戏做好准备。
我可以要求一些建议,解释吗?
我试过这个(仍然不知道如何将它移植到C或Java),但它允许客户端发送数字,即使其中一个只是猜测它。在我看来,kill_em_all
不能完成它的工作,它不会关闭所有连接,也不会断开其他客户端的连接。如何改善这个?
#!/usr/bin/env python
from random import randint
import socket, select
from time import gmtime, strftime
import threading
import sys
class Handler(threading.Thread):
def __init__(self, connection, randomnumber, server):
threading.Thread.__init__(self)
self.connection = connection
self.randomnumber = randomnumber
self.server = server
def run(self):
while True:
try:
data = self.connection.recv(1024)
if data:
print(data)
try:
num = int(data)
if self.server.guess(num) :
print 'someone guessed!'
self.server.kill_em_all()
break
else :
msg = "Try again!"
self.connection.sendall(msg.encode())
except ValueError as e:
msg = "%s" % e
self.connection.sendall(msg.encode())
else:
msg = "error"
self.connection.send(msg.encode())
except socket.error:
break
self.connection.close()
def send(self, msg):
self.connection.sendall(msg)
def close(self):
self.connection.close()
class Server:
randnum = randint(1,100)
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.address = (self.ip, self.port)
self.server_socket = None
def guess(self, no):
if self.randnum == no:
self.randnum = randint(1, 100)
print("New number is ", self.randnum )
result = True
else:
result = False
return result
def kill_em_all(self):
for c in self.clients:
c.send("BYE!")
c.close()
def run(self):
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind((self.ip, self.port))
self.server_socket.listen(10)
self.clients = []
print('Num is %s' % self.randnum)
while True:
connection, (ip, port) = self.server_socket.accept()
c = Handler(connection, self.randnum, self)
c.start()
self.clients.append(c)
except socket.error as e:
if self.server_socket:
self.server_socket.close()
sys.exit(1)
if __name__ == '__main__':
s = Server('127.0.0.1', 7777)
s.run()
客户代码:
import socket
import sys
port = 7777
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
s.connect(('127.0.0.1', port))
except socket.error, (value, message):
if s:
s.close()
print "Could not open socket: " + message
sys.exit(1)
while True:
data = raw_input('> ')
s.sendall(data)
data = s.recv(1024)
if data:
if data == "BYE!":
break
else:
print "Server sent: %s " % data
s.close()
答案 0 :(得分:1)
登录。使用您拥有的任何协议,向服务器发送一条消息,告知其关闭。在服务器中,在收到关闭消息时终止您的应用程序。而已。对于我使用的任何操作系统来说,这都不是问题 - 进程的任何线程都可以终止该进程。