Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use python to realize simple chat function

Shulou Source: shulou.com Published: 2022-05-31 10:44:06 09月23日 Update

This article mainly introduces how to use python to achieve simple chat function related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this article on how to use python to achieve simple chat function will have a harvest, let's take a look at it.

Server:

From socket import socketdef main (): # create a socket object and specify which transport service to use socket () parentheses do not pass parameters default is tcpipv4 server = socket () # bind ip address and port (so you can distinguish between different services) the port can specify the recommended port server.bind (('10.7.152.123') after 1024 5650)) # enable snooping-listening client connects to server server.listen # check if the server has started print ('server started') # receive client connections through a loop And make the corresponding processing (providing services) while True: # receiving the client's connection accpet is a blocking method if there is no client connecting to the server # this method blocks the code will not be executed downward (the returned object is a meta-ancestor) client, addr = server.accept () print (str (addr) + 'successfully connected to the server.') While True: # decode decodes the received message print (client.recv (1024). Decode ('utf-8')) data = input (' server:') # judge if the message sent by the client appears bey or bye-bye jumps out of the loop if data = = 'bey' or data = =' bye': Break # encode transcodes the sent message client.send (data.encode ('utf-8')) # disconnects client.close () if _ _ name__ =' _ _ main__': main ()

Client:

From socket import socketdef main (): # create socket object client = socket () # Connect server client.connect (('10.7.152.123') 5650) while True: data = input ('client:') # send a message to the server client.send (data.encode ('utf-8')) if data = =' Bey' or data = = 'bye': break print (client.recv (1024). Decode ('utf-8')) client.colse () if _ _ name__ = =' _ main__': main ()

Running result:

This is the end of the article on "how to use python to achieve simple chat". Thank you for reading! I believe that everyone has a certain understanding of "how to use python to achieve simple chat function" knowledge, if you want to learn more knowledge, welcome to follow the industry information channel.

Tags: Services clients servers clients functions messages objects knowledge ports content sockets methods side articles loops monitoring blocking differences success code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi NVidia OPPO Reno Apple Huawei