python编写简易聊天室实现局域网内聊天功能

时间:2022-10-29 22:58:52

本文实例为大家分享了python实现局域网内聊天功能的具体代码,供大家参考,具体内容如下

功能:

可以向局域网内开启接收信息功能的ip进行发送信息,我们可以写两段端口不同的代码来实现在一台电脑上与自己聊天.

关键点:

要想实现此功能必须将程序的端口固定

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from socket import *
 
 
def udp_send(udp_socket):
  # 发送消息 接收用户输入内容
  send_mes = input("请输入发送内容:")
  # 接收用户输入ip
  ip = input("请输入ip地址:")
  # 接收用户输入端口号
  port = int(input("请输入端口号"))
  # 发送消息 内容进行编码
  udp_socket.sendto(send_mes.encode("gbk"), (ip, port))
 
 
def udp_recvfrom(udp_socket):
  # 接收消息 最多4096个字节
  get_mes, get_ip = udp_socket.recvfrom(4096)
  print("收到来自%s的消息:%s" % (str(get_ip), get_mes.decode("gbk")))
 
 
def main():
  # 创建套接字
  udp_socket = socket(AF_INET, SOCK_DGRAM)
  # 设置固定端口
  udp_socket.bind(("", 8889))
 
  while True:
    print("*" * 50)
    print("----------无敌聊天器----------")
    print("1.发送消息")
    print("2.接收消息")
    print("0.退出系统")
    print("*" * 50)
 
    user = input("请输入要执行的操作:")
 
    if user == "1":
 
      udp_send(udp_socket)
 
    elif user == "2":
 
      udp_recvfrom(udp_socket)
 
    elif user == "0":
      break
 
    else:
 
      print("输入有误")
  # 关闭套接字
  udp_socket.close()
 
 
if __name__ == "__main__":
  main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/wf134/article/details/78509362