python-socket作业

#客户端
import socket
import threading
import tkinter
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 5550))

flag = False
class Connection:
    def __init__(self):
        self.win = tkinter.Tk()  # 创建主窗口
        self.win.title('登陆界面')
        self.win.geometry("400x400+200+20")
        self.labelName = tkinter.Label(self.win, text='账号').grid(row=0, column=0)
        self.labelPasswd = tkinter.Label(self.win, text='密码').grid(row=2, column=0)

        self.name = tkinter.Variable()
        self.word = tkinter.Variable()

        self.entryName = tkinter.Entry(self.win, textvariable=self.name).grid(row=0, column=1)
        self.entryPasswd = tkinter.Entry(self.win, show='*',width =20,textvariable= self.word).grid(row=2, column=1)

        self.text = tkinter.Text(self.win, height=10, width=20)
        self.text.grid(row=5, column=1)
        self.labeltext = tkinter.Label(self.win, text='消息').grid(row=5, column=0)

        self.button1 = tkinter.Button(self.win, text="连接", command=self.connect).grid(row=8, column=1)
        self.win.mainloop()

    def connect(self):

        username = self.name.get()
        password = self.word.get()
        userinfo = username + '$' + password
        sock.send(userinfo.encode())
        info = sock.recv(1024).decode()

        if info == '0':
            printStr = "账号或密码失败\n"
            self.text.insert(tkinter.INSERT, printStr)
            return
        else:
            printStr = "welcome to server!\n"
            self.text.insert(tkinter.INSERT, printStr)

        global flag
        flag = True
        self.win.destroy()                                          #连接成功关闭窗体

class Communicate:
    def __init__(self):
        self.win = tkinter.Tk()  # 创建主窗口
        self.win.title('聊天室')
        self.win.geometry("400x300+200+20")

        self.mesg = tkinter.Variable()  # 发送的信息
        self.labelmesg = tkinter.Label(self.win, text='说话').grid(row=4, column=0)
        self.entrymesg = tkinter.Entry(self.win, textvariable=self.mesg).grid(row=4, column=1)

        self.text = tkinter.Text(self.win, height=10, width=40)
        self.text.grid(row=5, column=1)
        self.labeltext = tkinter.Label(self.win, text='消息').grid(row=5, column=0)

        button2 = tkinter.Button(self.win, text="发送", command=self.sendThreadFunc).grid(row=8, column=2)

        th2 = threading.Thread(target=self.recvThreadFunc)
        th2.setDaemon(True)
        th2.start()
        self.win.mainloop()

    def sendThreadFunc(self):
        try:
            myword = self.mesg.get()
            self.mesg.set('')
            sock.send(myword.encode())
            if myword =='exit':
                printStr = "你的聊天结束\n"
                self.text.insert(tkinter.INSERT, printStr)
                sock.close()
        except ConnectionAbortedError:
            printStr = "服务器终止了连接\n"
            self.text.insert(tkinter.INSERT, printStr)
            sock.close()
        except ConnectionResetError:
            printStr = "服务器崩了\n"
            self.text.insert(tkinter.INSERT, printStr)
            sock.close()

    def recvThreadFunc(self):
        while True:
            try:
                otherword = sock.recv(1024).decode()
                otherword = otherword +'\n'
                if otherword:
                    self.text.insert(tkinter.INSERT, otherword)
                else:
                    pass
            except ConnectionAbortedError:
                printStr = "服务器终止了连接\n"
                self.text.insert(tkinter.INSERT, printStr)
                sock.close()
                break
            except ConnectionResetError:
                printStr = "服务器崩了\n"
                self.text.insert(tkinter.INSERT, printStr)
                sock.close()
                break

    def shut_down(self):
        self.win.destroy()

#--------------------------用户窗体

if __name__ =='__main__':
    deng = Connection()
    if flag :
        liao = Communicate()

#服务器端
import socket
import threading

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.bind(('localhost', 5550))

sock.listen(5)
print('Server', socket.gethostbyname('localhost'), 'listening ...')

mydict = dict()
mylist = list()

account = {'123':'123','456':'456','root':'xiuwenL'}
name = ['123','456','789']

# 把whatToSay传给除了exceptNum的所有人
def tellOthers(exceptNum, whatToSay):
    for c in mylist:
        #if c.fileno() != exceptNum:
            try:
                c.send(whatToSay.encode())
            except:
                pass

def subThreadIn(myconnection, connNumber,nickname):
    #nickname = myconnection.recv(1024).decode()
    mydict[myconnection.fileno()] = nickname
    mylist.append(myconnection)
    print('connection', connNumber, ' has nickname :', nickname)
    tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 进入聊天室】')
    while True:
        try:
            recvedMsg = myconnection.recv(1024).decode()
            if recvedMsg:
                if recvedMsg =='exit':                                                          #用户退出
                    mylist.remove(myconnection)
                    print(mydict[connNumber], 'exit, ', len(mylist), ' person left')
                    tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 离开聊天室】')
                    myconnection.close()
                    return

                print(mydict[connNumber], ':', recvedMsg)
                tellOthers(connNumber, mydict[connNumber] + ' :' + recvedMsg)

        except (OSError, ConnectionResetError):
            try:
                mylist.remove(myconnection)
            except:
                pass
            print(mydict[connNumber], 'exit, ', len(mylist), ' person left')
            tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 离开聊天室】')
            myconnection.close()
            return

while True:
    connection, addr = sock.accept()
    while True:
        try:
            # connection.settimeout(5)
            suc = False
            buf = connection.recv(1024).decode()
            buf = buf.split('$')
            if buf[0] in account.keys() and buf[1] in account.values() :
                print('Accept a new connection', connection.getsockname(), connection.fileno())
                connection.send(b'1')
                suc = True

            else:
                connection.send(b'0')

            if suc :                        #只有登陆成功才加入线程
                # 为当前连接开辟一个新的线程
                mythread = threading.Thread(target=subThreadIn, args=(connection, connection.fileno(),buf[0]))
                mythread.setDaemon(True)
                mythread.start()
                break
        except:
            connection.close()

posted @ 2018-09-19 16:36  xiuwenL  阅读(180)  评论(0编辑  收藏  举报