Python socket implementation Simple Chat room

Source: Internet
Author: User

By referring to other cattle articles and code, and then summing up according to their own understanding, the explanation has been added to the note, FYI

Main Reference article: http://blog.csdn.net/dk_zhe/article/details/37820965

Http://www.cnblogs.com/coser/archive/2012/01/06/2315216.html

Https://docs.python.org/2.7/library/select.html?highlight=select#module-select

Http://www.cnblogs.com/devinzhang/archive/2012/01/13/2321826.html

Http://blog.chinaunix.net/uid-23146151-id-3084687.html

server.py and client.py

#Coding=utf-8#to establish a network connection through the socket:#requires at least 2 sockets, both server and client#need to establish a connection between sockets to send and receive data via a connection#client and server connection processes:#1. Set up the server socket, bind the host and port, and listen to the client's connection request#2. The client socket sends a connection request based on the server's address, connected to the server socket, and the client socket needs to provide its own socket FD so that the server socket responds#3. When the server hears the client connection request, it responds to the request, establishes a new thread, and sends the server FD to the client#then, the server continues to listen for other client requests, while client and server cross-connect data traffic through the socket connectionImportSocket,select,threadhost=socket.gethostname () port= 5963server_addr=(Host,port)#Waitable's Read list, which represents the lists of readable socket objects in asynchronous communicationInputs = []#name of the client connecting to the serverFd_name = {}#Create and initialize the server socketdefServerinit (): SS= Socket.socket ()#Create a server socketSs.bind (SERVER_ADDR)#binding to Server addrSs.listen (10)#Listening port number, setting maximum number of listeners    returnSs#returns the initialized server socket#to create a new socket connectiondefnewconnection (ss): Client_conn,client_addr= Ss.accept ()#responds to a client connection request, establishes a connection that can be used to transfer data    Try:        #send welcome message to client sideClient_conn.send ("Welcome to Chatroom,pls set up your Nick name!") Client_name= CLIENT_CONN.RECV (1024)#receives the nickname from the client, the maximum receive character is 1024x768inputs.append (client_conn) Fd_name[client_conn]= Client_name#Adding a connection/connection name to a key-value pairClient_conn.send ("Current members in chatroom is:%s"%fd_name.values ())#send new members to all connections join information         forOtherinchFd_name.keys ():ifOther! = Client_conn andOther! =ss:other.send (Fd_name[client_conn]+"joined the chatroom!")    exceptException as E:Printedefcloseconnection ():PassdefRun (): SS=Serverinit () inputs.append (ss)Print "server is running ..."     whileTrue:#rlist,wlist,elist = select.select (inputs, [], inputs,100) # If the server is only turned on, there is no client connection within 100s, it also times outRlist,wlist,elist =Select.select (inputs, [], [])#when there is no readable FD, indicates a server error, exiting the server        if  notrlist:Print "timeout ..."ss.close ()#close the server socket             Break         forRinchrlist:ifR isSs:#server socket, indicating a new client connection requestnewconnection (ss)Else:#indicates that a client connection has data to reach the serverDisconnect =FalseTry: Data= R.RECV (1024)#Receive Datadata = Fd_name[r] +" : "+ Data#identify the client nickname                exceptSocket.error:data= Fd_name[r] +"leaved The"Disconnect=TrueElse:                    Pass                ifDisconnect:inputs.remove (R)PrintData forOtherinchInputs:ifOther! = SS andOther! = r:#does not occur to the server and disconnected connections                            Try: Other.send (data)exceptException as E:PrinteElse:                                Pass                    #delisting                    delFd_name[r]Else:                    PrintData#displaying data sent by the client on the server                    #send the same information to other members (connections)                     forOtherinchInputs:ifOther! = SS andOther! =r:Try: Other.send (data)exceptException as E:Printeif __name__=="__main__": Run ()
#Coding=utf-8#because the experiment is running on this machine, the server addr = = Client AddrImportSocket,select,threading,syshost=socket.gethostname () client_addr= (host,5963)#equals server_addr ()#listen to other members of the conversationdefListening (CS): Inputs=[CS] whiletrue:rlist,wlist,elist=Select.select (inputs, [], [])#The client socket is used to send and receive data, because there is only this waitable object, so there is no need to iterate        ifCsinchrlist:Try:                #print data received from the server                PrintCS.RECV (1024)            exceptSocket.error:Print "Socket is error"exit ()#Speechesdefspeak (CS): whileTrue:Try: Data=raw_input ()exceptException as E:PrintR"can ' t input"exit ()#if data = = "Exit":        #cs.close ()        # Break        Try: Cs.send (data)exceptException as E:exit ()defMain ():#Client SocketCS =Socket.socket () cs.connect (CLIENT_ADDR)#start listening and speaking threads separatelyt = Threading. Thread (target=listening,args= (CS,))#Note that this is required when there is only one element in the tuple, otherwise it will be considered the original type .T.start () T1= Threading. Thread (target=speak,args=(CS,)) T1.start ()if __name__=="__main__": Main ()

Python socket implementation Simple Chat room

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.