Python socket chat room program, pythonsocket chat room

Source: Internet
Author: User

Python socket chat room program, pythonsocket chat room

Today, we use the python socket module to implement a chat room program.

Although the functions are relatively simple, there are still some basic functions.

Hope you can give me some advice.


Server programs:

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 () # Pass whatToSay to the owner def tellOthers (usually tnum, whatToSay): for c in mylist: if c. fileno ()! = Repeated tnum: try: c. send (whatToSay. encode () failed T: passdef subThreadIn (myconnection, connNumber): nickname = myconnection. recv (1, 1024 ). decode () mydict [myconnection. fileno ()] = nickname mylist. append (myconnection) print ('connection', connNumber, 'has nickname: ', nickname) tellOthers (connNumber,' [system prompt: '+ mydict [connNumber] +' enter the chat room] ') while True: try: recvedMsg = myconnection. recv (1, 1024 ). decode () if RecvedMsg: print (mydict [connNumber], ':', recvedMsg) tellOthers (connNumber, mydict [connNumber] + ':' + recvedMsg) Consumer T (OSError, ConnectionResetError): try: mylist. remove (myconnection) Counter T: pass print (mydict [connNumber], 'exit, ', len (mylist), 'person left') tellOthers (connNumber,' [system prompt: '+ mydict [connNumber] +' exit chat room] ') myconnection. close () returnwhile True: connection, addr = sock. accept () pri Nt ('Accept a new connection', connection. getsockname (), connection. fileno () try: # connection. settimeout (5) buf = connection. recv (1, 1024 ). decode () if buf = '1': connection. send (B 'welcome to server! ') # Create a new thread for the current connection mythread = threading. thread (target = subThreadIn, args = (connection, connection. fileno () mythread. setDaemon (True) mythread. start () else: connection. send (B 'please go out! ') Connection. close () failed T: pass

Client Program:

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()

Code execution:

Chat process 1:



System Monitoring:



Chat process 2:



System Monitoring:



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.