Group Chat Service Side
The service-side server.py code is as follows:
#-*-Coding:utf-8-*-#!/usr/bin/env python # @Time: 2018/5/18 16:05# @Desc: Group chat Server # @File: server.py# @Softwa Re:pycharmimport socket, selecthost = Socket.gethostname () port = 5999addr = (host, port) inputs = []fd_name = {} ' "" Traverse Group member " "" Def Who_in_room (w): Name_list = [] for k in W:name_list.append (W[k]) return name_list "" "Connection" "" Def Conn ( ): print "server start run" SS = Socket.socket () ss.bind (addr) Ss.listen (5) return SS "" "Add new Group member" "" Def new_coming (ss ): client, add = ss.accept () print ' Welcome%s%s '% (client, add) Wel = ' Welcome to the chat room. Please enter your name: "' Try:client.send (wel) name = CLIENT.RECV (1024x768) inputs.append (client) FD_NAME[CL Ient] = Name NameList = "The group member of the online chat is%s"% (Who_in_room (fd_name)) Client.send (namelist) except Exception, E:print e "" "Traverse Chat Message" "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 (1024x768) data = Fd_name[temp] + "say:" + data except socket. Error:data = Fd_name[temp] + "Leave chat room" disconnect = True if disconnect : Inputs.remove (temp) print data for other in inputs: If other! = SS and Other! = Temp:try:other.send (da TA) 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) ExceptException, e:print e if __name__ = = ' __main__ ': Server_run ()
Group chat Client
The client client.py code is as follows:
#-*-Coding:utf-8-*-#!/usr/bin/env python # @Time: 2018/5/18 16:06# @Desc: Group chat client # @File: client.py# @Softwa Re:pycharm import socket, select, Threadinghost = Socket.gethostname () addr = (host, 5999) "" "Connection" "Def Conn (): s = sock Et.socket () s.connect (addr) return S "" "Get Group Member" "Def Lis (s): my = [s] While True:r, W, E = Select.selec T (my, [], []) if s in R:try:print s.recv (1024x768) except Socket.error: Print "Communication exception" exit () "" "Input chat" "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 () "" "Main function, create chat and get group member thread" "" Def Main (): SS = conn () T = Threadi Ng. Thread (Target=lis, args= (SS,)) T.start () T1 = Threading. Thread (Target=talk, args= (SS,)) T1.start () if __name__ = = ' __main__ ': main()
Start the server-side code, then start the client (start a, representing a group member, can be multiple) code, the execution results are as follows:
Python implements group chat applet code