Python socket聊天室程式,pythonsocket聊天室

來源:互聯網
上載者:User

Python socket聊天室程式,pythonsocket聊天室

今天用python的socket模組實現了一個聊天室的程式

雖然功能比較簡單,但是該有的準系統還是有的

還望大家指點


伺服器端程式:

import socketimport threadingsock = 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()#把whatToSay傳給除了exceptNum的所有人def tellOthers(exceptNum, whatToSay):    for c in mylist:        if c.fileno() != exceptNum :            try:                c.send(whatToSay.encode())            except:                passdef subThreadIn(myconnection, connNumber):    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:                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()            returnwhile True:    connection, addr = sock.accept()    print('Accept a new connection', connection.getsockname(), connection.fileno())    try:        #connection.settimeout(5)        buf = connection.recv(1024).decode()        if buf == '1':            connection.send(b'welcome to server!')            #為當前串連開闢一個新的線程            mythread = threading.Thread(target=subThreadIn, args=(connection, connection.fileno()))            mythread.setDaemon(True)            mythread.start()                    else:            connection.send(b'please go out!')            connection.close()    except :          pass

用戶端程式:

import socketimport timeimport threadingsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(('localhost', 5550))sock.send(b'1')print(sock.recv(1024).decode())nickName = input('input your nickname: ')sock.send(nickName.encode())def sendThreadFunc():    while True:        try:            myword = input()            sock.send(myword.encode())            #print(sock.recv(1024).decode())        except ConnectionAbortedError:            print('Server closed this connection!')        except ConnectionResetError:            print('Server is closed!')    def recvThreadFunc():    while True:        try:            otherword = sock.recv(1024)            if otherword:                print(otherword.decode())            else:                pass        except ConnectionAbortedError:            print('Server closed this connection!')        except ConnectionResetError:            print('Server is closed!')th1 = threading.Thread(target=sendThreadFunc)th2 = threading.Thread(target=recvThreadFunc)threads = [th1, th2]for t in threads :    t.setDaemon(True)    t.start()t.join()

代碼執行:

聊天過程1:



系統監視:



聊天過程 2 :



系統監視:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.