Python實現群聊天小程式代碼

來源:互聯網
上載者:User

標籤:輸入   utf-8   一個   exception   客戶   port   error   socket   pen   

群聊服務端

服務端Server.py代碼如下:

# -*- coding: utf-8 -*-#!/usr/bin/env python # @Time    : 2018/5/18 16:05# @Desc    : 群聊服務端# @File    : Server.py# @Software: PyCharmimport socket, selecthost = socket.gethostname()port = 5999addr = (host, port)inputs = []fd_name = {} """遍曆群成員"""def who_in_room(w):    name_list = []    for k in w:        name_list.append(w[k])    return name_list """串連"""def conn():    print "服務端開始運行"    ss = socket.socket()    ss.bind(addr)    ss.listen(5)    return ss """添加新的群成員"""def new_coming(ss):    client, add = ss.accept()    print ‘歡迎 %s %s‘ % (client, add)    wel = ‘‘‘歡迎進入聊天室 . 請輸入你的名字:‘‘‘    try:        client.send(wel)        name = client.recv(1024)        inputs.append(client)        fd_name[client] = name        nameList = "已線上聊天的群成員是 %s" % (who_in_room(fd_name))        client.send(nameList)    except Exception, e:        print e """遍曆聊天資訊"""def server_run():    ss = conn()    inputs.append(ss)    while True:        r, w, e = select.select(inputs, [], [])        for temp in r:            if temp is ss:                new_coming(ss)            else:                disconnect = False                try:                    data = temp.recv(1024)                    data = fd_name[temp] + " 說 : "+ data                except socket.error:                    data = fd_name[temp] + "離開聊天室"                    disconnect = True                if disconnect:                    inputs.remove(temp)                    print data                    for other in inputs:                        if other != ss and other != temp:                            try:                                other.send(data)                            except Exception, e:                                print e                    del fd_name[temp]                else:                    print data                    for other in inputs:                        if other != ss and other != temp:                            try:                                other.send(data)                            except Exception, e:                                print e  if __name__ == ‘__main__‘:    server_run()
群聊用戶端

用戶端Client.py代碼如下:

# -*- coding: utf-8 -*-#!/usr/bin/env python # @Time    : 2018/5/18 16:06# @Desc    : 群聊用戶端# @File    : Client.py# @Software: PyCharm import socket, select, threadinghost = socket.gethostname()addr = (host, 5999) """串連"""def conn():    s = socket.socket()    s.connect(addr)    return s """擷取群成員"""def lis(s):    my = [s]    while True:        r, w, e = select.select(my, [], [])        if s in r:            try:                print s.recv(1024)            except socket.error:                print "通訊出現異常"                exit() """輸入聊天"""def talk(s):    while True:        try:            info = raw_input()        except Exception, e:            print ‘can\‘t input‘            exit()        try:            s.send(info)        except Exception, e:            print e            exit() """主函數,建立聊天和擷取群成員線程"""def main():    ss = conn()    t = threading.Thread(target=lis, args=(ss,))    t.start()    t1 = threading.Thread(target=talk, args=(ss,))    t1.start()  if __name__ == ‘__main__‘:    main() 

先啟動服務端代碼,後啟動用戶端(啟動一個,代表一個群成員,可多個)代碼,執行結果如下:  

 

 

 

Python實現群聊天小程式代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.