Demo entry 6645694

py

   

Submitted by lu on Oct 11, 2017 at 10:28
Language: Python 3. Code size: 6.4 kB.

# -*- coding: utf-8 -*-

'a server example which send hello to client.'
from PyQt5 import QtCore, QtGui, QtWidgets
import time, threading, socket,sys
from ui_server import Ui_server
HOST = '127.0.0.1'
PORT = 8880

class server(object):

    info = {
        'admin': {
            'password': '8888',
            'isconnet': False,
            'socket': None,
        },

        'admin2': {
            'password': '8888',
            'isconnet': False,
            'socket': None,
        },

        'admin3': {
            'password': '8888',
            'isconnet': False,
            'socket': None,
        },

    }



    def __init__(self):
        self.isconnet = False
        self.app = QtWidgets.QApplication(sys.argv)
        self.mainWindow = Ui_server()
        self.mainWindow.openButton.clicked.connect(self.openBtnClicked)
        self.model = QtGui.QStandardItemModel(self.mainWindow.log)



    def connect(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.s.bind((HOST,PORT))
        self.s.listen(0)

        tmp = QtGui.QStandardItem()
        mesg = '- 等待新链接...'
        tmp.setText(mesg)
        self.model.appendRow(tmp)
        self.mainWindow.log.setModel(self.model)
        self.mainWindow.log.update()


    def Accept(self):

        sock, addr = self.s.accept()

        tmp = QtGui.QStandardItem()
        mesg = '- 接受来自 %s:%s 的新链接...' % addr
        tmp.setText(mesg)
        self.model.appendRow(tmp)
        self.mainWindow.log.setModel(self.model)
        self.mainWindow.log.update()


        return sock, addr

    def Verify(self, sock):

        tmp = QtGui.QStandardItem()
        mesg = '- 正在验证...'
        tmp.setText(mesg)
        self.model.appendRow(tmp)
        self.mainWindow.log.setModel(self.model)
        self.mainWindow.log.update()

        time.sleep(0.5)
        name = sock.recv(1024).decode('utf-8').strip()
        time.sleep(0.5)
        password = sock.recv(1024).decode('utf-8')

        # 错误:用户不存在
        if name not in self.info.keys():
            time.sleep(0.5)
            sock.send(bytes('notexist', 'utf-8'))
            sock.close()
            return None

        # 错误:密码错误
        elif password != self.info[name]['password']:
            time.sleep(0.5)
            sock.send(bytes('passwerror', 'utf-8'))
            sock.close()
            return None

        # 错误:用户已登录
        elif self.info[name]['isconnet'] == True:
            sock.send(bytes('exist', 'utf-8'))
            sock.close()
            return None

        else:
            time.sleep(0.5)
            sock.send(bytes('Welcome', 'utf-8'))
            self.info[name]['socket'] = sock
            self.info[name]['isconnet'] = True

        return name




    def sendToEveryone(self,name,meg):
        if name == None:
            for each in self.info.keys():
                if self.info[each]["isconnet"]:
                    try:
                        tmpSock = self.info[each]["socket"]
                        tmpSock.send(bytes(meg, "utf-8"))
                    except BaseException as ex:
                        print(ex)
                        self.info[each]["isconnet"] = False
                        del self.info[each]["socket"]
                        self.info[each]["socket"] = None
        else:
            for each in name:
                if self.info[each]["isconnet"]:
                    try:
                        tmpSock = self.info[each]["socket"]
                        tmpSock.send(bytes(meg, "utf-8"))
                    except BaseException as ex:
                        print(ex)
                        self.info[each]["isconnet"] = False
                        del self.info[each]["socket"]
                        self.info[each]["socket"] = None


    def privateChat(self,msg):
        if msg == '' or msg[0] !='@':
            username = None
            sendmsg = msg
        else:
            blankspace = ' '
            str_index = msg.index(blankspace)
            username = [msg[1:str_index]]
            sendmsg = msg[str_index+1:]

        return username,sendmsg


    def TransferStation(self, sock, addr):
        time.sleep(2)

        try:
            while True:
                time.sleep(0.5)
                data = sock.recv(1024).decode('utf-8')
                name,meg = self.privateChat(data)
                if name != None:
                    name.append(threading.current_thread().getName())
                    name = set(name)
                self.sendToEveryone(name,threading.current_thread().getName() + ":\n"+'  ' + data)
        except BaseException as ex:
            print(ex)
            self.info[threading.current_thread().getName()]["isconnet"] = False
            del self.info[threading.current_thread().getName()]["socket"]
            self.info[threading.current_thread().getName()]["socket"] = None

            tmp = QtGui.QStandardItem()
            mesg = '链接 %s:%s 关闭.' % addr
            tmp.setText(mesg)
            self.model.appendRow(tmp)
            self.mainWindow.log.setModel(self.model)
            self.mainWindow.log.update()

    def listener(self):
        global count
        while True:
            count += 1
            #time.sleep(3)
            sock, addr = self.Accept()
            sender = self.Verify(sock)

            tmp = QtGui.QStandardItem()
            mesg = '第 %d 个用户 [%s] 已经登录:\n' % (count,sender)
            tmp.setText(mesg)
            self.model.appendRow(tmp)
            self.mainWindow.log.setModel(self.model)
            self.mainWindow.log.update()


            if sender is not None and sender in self.info.keys() and self.info[sender]['isconnet']:
                # 创建新线程来处理TCP连接:
                self.th = threading.Thread(target=self.TransferStation, args=(sock, addr))
                self.th.setName(sender)
                self.th.start()

    def openBtnClicked(self):
        global count
        count = 0
        self.connect()
        threading.Thread(target=self.listener).start()


if __name__ == '__main__':
    aserver = server()
    aserver.mainWindow.show()
    aserver.app.exec_()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).