如何在一个简单的UDP聊天工具中实现文件传输和GoBackN?

2024-04-26 01:26:22 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的项目,我需要创建一个简单的UDP客户端/服务器聊天工具,可以处理文本/表情/图片。为此,我必须实现文件传输并返回到现有代码中。 这是我的客户端和服务器代码

client.py

import socket

# create our udp socket
try:
    socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
    print("Oops, something went wrong connecting the socket")
    exit()

while 1:
    message = input("> ")

    # encode the message
    message = message.encode()

    try:
        # send the message
        socket.sendto(message, ("10.0.1.29", 9999))

        # output the response (if any)
        data, ip = socket.recvfrom(1024)

        print("{}: {}".format(ip, data.decode()))

    except socket.error:
        print("Error! {}".format(socket.error))
        exit()```


server.py

import socket
import emoji
# set up the socket using local address
socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket.bind(("", 9999))

while 1:

    # get the data sent to us
    data, ip = socket.recvfrom(1024)

    # display
    print("{}: {}".format(ip, data.decode(encoding="utf-8").strip()))

    # echo back
    socket.sendto(data, ip)


Any help at all would be appreciated

Tags: the代码pyimportip服务器format客户端