python simple chat room to achieve LAN chat function
- 2020-11-20 06:10:31
- OfStack
This article is an example of python to share the realization of the LAN chat function of the specific code for your reference, the specific content is as follows
Function:
We can send messages to ip, which turns on the function of receiving messages in the LAN. We can write two pieces of code with different ports to realize chatting with ourselves on one computer.
Key points:
To do this, the program's port must be fixed
from socket import *
def udp_send(udp_socket):
# Send a message Receive user input
send_mes = input(" Please enter send content :")
# Receiving user input ip
ip = input(" Please enter the ip address :")
# Receives the user input port number
port = int(input(" Please enter the port number "))
# Send a message Encoding of content
udp_socket.sendto(send_mes.encode("gbk"), (ip, port))
def udp_recvfrom(udp_socket):
# Receives the message most 4096 bytes
get_mes, get_ip = udp_socket.recvfrom(4096)
print(" Received from %s The news of the :%s" % (str(get_ip), get_mes.decode("gbk")))
def main():
# Create the socket
udp_socket = socket(AF_INET, SOCK_DGRAM)
# Set fixed port
udp_socket.bind(("", 8889))
while True:
print("*" * 50)
print("---------- Invincible chatterbox ----------")
print("1. Send a message ")
print("2. Receives the message ")
print("0. Log out ")
print("*" * 50)
user = input(" Please enter the action to perform :")
if user == "1":
udp_send(udp_socket)
elif user == "2":
udp_recvfrom(udp_socket)
elif user == "0":
break
else:
print(" Input is wrong ")
# Close the socket
udp_socket.close()
if __name__ == "__main__":
main()