Python 网络通讯 使用socket接收和发送信息

EN
EN
2023-04-05 / 0 评论 / 67 阅读 / 正在检测是否收录...

lsy9kia5.png

发送消息

'''
发送消息
'''

# 1. 导入内置socket
import socket

# 2. 创建套接字对象
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 3. 指定发送地址
''' ip  port '''
dest_address = ('192.168.0.197', 8080)

# 4. 创建要发送的信息
send_message = input("请输入要发送的消息")

# 5. 通过socket对象将消息发送
#    需要对字符进行编码
udp_socket.sendto(send_message.encode("utf-8"),dest_address)

# 6. 关闭
udp_socket.close()
接收消息

'''
接收消息
'''
# 1. 导入内置socket
import socket

# 2. 创建套接字对象
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 3.绑定本机消息
''' 
如果IP地址为空,默认为本机的ip
'''
localhost_address = ('',7788)
udp_socket.bind(localhost_address)

# 4. 等待接收消息
'''
接收的消息是一个元组
第一个元素 是 消息内容
第二个元素 是 当前发送方的地址
'''
recv_msg = udp_socket.recvfrom(1024); # 1024 本次能够接收的最大消息字节数

# 5. 显示消息
print(recv_msg[0].decode("utf-8")) # 内容解码
print(recv_msg[1])

# 6. 关闭
udp_socket.close()

print(",,,")
DEMO

import socket

def send(udp_socket):
    msg = input("请输入要发送的消息")
    dest_address = ('192.168.0.197', 8080)
    udp_socket.sendto(msg.encode("utf-8"), dest_address)

def recv(udp_socket):
    recv_msg = udp_socket.recvfrom(1024);  # 1024 本次能够接收的最大消息字节数
    msg = recv_msg[0].decode("utf-8")
    recv_IP = recv_msg[1]
    print(f'消息:{msg} 来自 {recv_IP}')

def main():

    # 创建
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # 绑定本机消息
    udp_socket.bind( ('',7788) )

    # 死循环 保证程序一直运行

    while True:
        print('=' * 30)
        print("1.发送消息")
        print("2.接收消息")
        print("3.结束聊天")
        print("=" * 30)

        op_num = input("请输入操作序号")
        if op_num == '1':
            # 发送消息
            send(udp_socket)
            pass
        elif op_num == '2':
            # 接收消息
            recv(udp_socket)
            pass
        elif op_num == '3':
            # 结束聊天
            break
        else:
            print("输入有误")
    udp_socket.close()
    print("关闭聊天")

if __name__ == '__main__':
    main()
0

评论 (0)

取消