线程python套接字服务器

时间:2015-12-19 22:01:47

标签: python multithreading sockets python-3.x

我有一个Multihtreaded服务器与python可以处理客户端请求,但我有一个问题。 在我的Server Class我有一个start函数,它开始像这样听取客户:

class Server:
    def __init__(self, clients={}):
        self.clients = clients
        self.ip = 'localhost'
        self.port = ****
        self.pattern = '(C\d)'


def start(self):
    self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.s.bind((self.ip, self.port))
    self.s.listen(10)
    while 1:
        clientsock, addr = self.s.accept()
        print ('Connected with ' + addr[0] + ':' + str(addr[1]))
        _thread.start_new_thread(self.handler, (clientsock, addr))
def handler(self, clientsock, addr):
    data = clientsock.recv(BUFF)
    print ('Data : ' + repr(data))
    data = data.decode("UTF-8")
    result = re.match(self.pattern, data)
    print (data)
    if(result):
        self.registerClient(clientsock, data)
    if(data == "Exit"):
        self.exitClient(clientsock)
def server_response(self, message, flag, err):
    if(flag):
        res = message.encode('utf-8')
        return res
    else:
        res = message.encode('utf-8')+ "[ ".encode('utf-8')+err.encode('utf-8')+ " ]".encode('utf-8')
        return res

def registerClient(self, clientsock, data):
    if(data in self.clients):
        err = "Error : Client Name Exist!"
        clientsock.send(self.server_response('Reg#NOK#', 0, err))
        clientsock.close()
        sys.exit(1)
    self.clients[clientsock] = data
    clientsock.send(self.server_response('Reg#OK', 1, ''))
def exitClient(self, clientsock):
    try:
        f = self.clients.pop(clientsock)
        clientsock.send(self.server_response('BYE#OK', 1, ''))
        clientsock.close() 
    except KeyError:
        err = "Error : Client Doesn't Connected To Server!"
        clientsock.send(self.server_response('BYE#NOK#', 0, err))
        clientsock.close()
        sys.exit(1)

这是我的client Class

class Client:
    def __init__(self, name):
        self.name = name
        self.ip = '127.0.0.1'
        self.next_client = None
        self.s = ""
        try:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except:
            print ('Reg#NOK#[ ' + msg[1] + ' ]')
            sys.exit()
def register(self, server):
    self.s.connect((server.ip, server.port))
    message = self.name
    try:
        self.s.sendall(bytes(message, 'UTF-8'))
    except (socket.error):
        print ('Send Failed')
        sys.exit()

    reply = self.s.recv(4096)
    print ("Respose From Server : " + reply.decode("utf-8") )
def exitFromServer(self, server):
    message = "Exit".encode('utf-8')
    try:
        a = self.s.sendall(message)
    except (socket.error):
        print ('Send Failed')
        sys.exit()

    reply = self.s.recv(4096)

这是主要文件:

from server import *
from client import *
import _thread

a = Server()
_thread.start_new_thread(a.start, ())
b = Client("C1")
b.register(a)
b.exitFromServer(a)

正如你所看到的,当Server class调用启动函数时,没有可以处理创建Client的线程,我的意思是当我使用这样的启动函数时,没有程序可以继续在主文件中,我知道我应该在这里使用另一个线程但是在哪里和如何,我使用Python 3.4,谢谢你的帮助。

修改

开始的问题已解决,感谢tdelaney, 但是当我运行它时只有register函数有效且exitFromServer没有做任何事情你能告诉我问题在哪里。程序在执行register函数之后执行任何操作并且它似乎是为某事而战。

2 个答案:

答案 0 :(得分:0)

这意味着什么?

import threading
from server import *
from client import *

global a
a = Server()
def sServer():
    global a
    a.start()

def cClient():
    global a
    b = Client("C1")
    b.register(a)


s = threading.Thread(name='server', target=sServer)
c = threading.Thread(name='client', target=cClient)

s.start()
c.start()

答案 1 :(得分:0)

Server Class我必须在while True函数之后添加另一个handler循环,因为它应该在客户端请求之前完成所有客户端请求:

def handler(self, clientsock, addr):
    while 1:
        data = clientsock.recv(BUFF)
        print ('Data : ' + repr(data))
        data = data.decode("UTF-8")
        result = re.match(self.pattern, data)
        if(result):
            self.registerClient(clientsock, data)
        if(data == "Exit"):
            self.exitClient(clientsock)
            break