我在我的Python TCP程序中找不到我的逻辑或语法错误

2024-09-29 23:32:39 发布

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

我正在创建一个TCP服务器x客户机通信,但是我遇到了一个逻辑问题,我无法找出它发生的原因。我的sizeWindow的值以某种方式获得了以前的值并打破了我的窗口的大小。。。你知道吗

如您所见:

enter image description here

我需要找出为什么它从256到1024,它应该是512,但它不是。。。你知道吗

我的猜测是它没有更新sizeWindow值,但我无法找出原因。你知道吗

要测试我的项目,您需要服务器和客户机类:

服务器类(应首先运行该类):

# ServerTCP
import socket

MY_IP = "127.0.0.1"
PORT_NUMBER = 13000


# socket TCP/IP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


server_address = (MY_IP, PORT_NUMBER)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)

sock.listen(1)

while True:

    print('Waiting a connection')
    connection, client_address = sock.accept()
    try:
        print('Connection from ', client_address)

        while True:
            data = connection.recv(16)
            print('received {!r}'.format(data))
            if data:
                print('sending data back to the client')
                connection.sendall(data)
            else:
                print('no data came from ', client_address)
                break

    finally:
        connection.close()

这是我的客户机类(问题是……):

# ClientTCP - 4.0

import socket
import time

MY_IP = "127.0.0.1"
PORT_NUMBER = 13000

g_windowTime = 0

# socket TCP/IP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = (MY_IP, PORT_NUMBER)
sock.connect(server_address)

def execute():
    global g_windowTime
    g_windowTime = time.time()
    sizeWindow = 1
    id_packet = "1"
    packets_resend = []

    while True:
        packets_sent = []

        # Send data
        sizeWindow, packets_sent, id_packet = send_packets(sizeWindow, packets_sent, packets_resend, id_packet)

        # Waits for the amount
        amount_received = 0
        amount_expected = len(packets_sent)

        while amount_received < amount_expected:
            try:
                sock.settimeout(5.0)
                data = sock.recv(16)
                amount_received += len(data)
            except:
                print("The packet needs to be resend")
        sizeWindow = sizeWindow * 2
        tempo = (time.time() - g_windowTime) * 1000
        print(f'{str(round(tempo, 2)).replace(".", ",")}; {int(sizeWindow)}')
        if tempo > 10000:
            exit()


def send_packets(sizeWindow, packets_sent, packets_resend, id_packet):
    global g_windowTime
    i = 0
    j = 0
    timer = 0

    while i < sizeWindow:

        if packets_resend == []:
            packet = id_packet.encode('utf-8')
            id_packet = str(int(id_packet) + 1)
        elif packets_resend != []:
            packet = packets_resend.pop(0)

        if packet not in packets_sent:
            packets_sent.append(packet)

        # Send the packet
        try:
            sock.sendall(packet)
        except:
            print("Problem with sendall")
            connect()

        # Timer
        if (i == 0):
            timer = time.time()
        elif (i > 0) and (time.time() > (timer + 0.01)):
            if sizeWindow > 1:
                j = i + 1
                while j < sizeWindow:
                    packet = id_packet.encode('utf-8')
                    id_packet = str(int(id_packet) + 1)
                    packets_resend.append(packet)
                    j += 1
                sizeWindow = sizeWindow / 2
                currentTime = (time.time() - g_windowTime) * 1000
                print(f'{str(round(currentTime, 2)).replace(".", ",")}; {int(sizeWindow)}')

                send_packets(sizeWindow, packets_sent, packets_resend, id_packet)

        i += 1

    return sizeWindow, packets_sent, id_packet

def connect():
    sock.Connect(server_address)

execute()

sock.close()

我最好的猜测是,问题出在方法return sizeWindow, packets_sent, id_packetsend_packets中,它返回3次…,2次返回正确的sizeWindow值,但不知何故第三次它将sizeWindow的值更改为以前的值,在我的算法中产生了一个很大的问题。。。你知道吗

我不知道我是忘了什么还是语法错误,但我找不到为什么会这样。。。你知道吗

如果有人能找出原因,我会非常高兴的。你知道吗

非常感谢。你知道吗


Tags: ipiddataservertimepacketaddresssocket
1条回答
网友
1楼 · 发布于 2024-09-29 23:32:39

我发现了你的错误。在send_packets中,您有一个递归调用,您不会从中得到返回的sizeWindow。 应使用以下内容更新函数:

def send_packets(sizeWindow, packets_sent, packets_resend, id_packet):
    # [...]
    while i < sizeWindow:
        # [...]
        # Timer
        if (i == 0):
            timer = time.time()
        elif (i > 0) and (time.time() > (timer + 0.01)):
            if sizeWindow > 1:
                [...]
                sizeWindow, packets_sent, id_packet = send_packets(sizeWindow, packets_sent, packets_resend, id_packet)

        i += 1

    return sizeWindow, packets_sent, id_packet

下面是我用来调试一些打印错误的代码。你知道吗

import socket
import threading
import time


class Server(threading.Thread):

    def run(self) -> None:
        MY_IP = "127.0.0.1"
        PORT_NUMBER = 13000


        # socket TCP/IP
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


        server_address = (MY_IP, PORT_NUMBER)
        print('Server starting up on {} port {}'.format(*server_address))
        sock.bind(server_address)

        sock.listen(1)

        while True:

            print('Waiting a connection')
            connection, client_address = sock.accept()
            try:
                print('Connection from ', client_address)

                while True:
                    data = connection.recv(16)
                    #print('received {!r}'.format(data))
                    if data:
                        #print('sending data back to the client')
                        connection.sendall(data)
                    else:
                        print('no data came from ', client_address)
                        break

            finally:
                connection.close()

class Client(threading.Thread):

    def run(self) -> None:
        MY_IP = "127.0.0.1"
        PORT_NUMBER = 13000

        g_windowTime = 0

        # socket TCP/IP
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        server_address = (MY_IP, PORT_NUMBER)
        sock.connect(server_address)

        def execute():
            global g_windowTime
            g_windowTime = time.time()
            sizeWindow = 1
            id_packet = "1"
            packets_resend = []

            while True:
                packets_sent = []

                # Send data
                sizeWindow, packets_sent, id_packet = send_packets(sizeWindow, packets_sent, packets_resend, id_packet)
                print(f"Send packet returned: {sizeWindow}")

                # Waits for the amount
                amount_received = 0
                amount_expected = len(packets_sent)

                while amount_received < amount_expected:
                    try:
                        sock.settimeout(5.0)
                        data = sock.recv(16)
                        amount_received += len(data)
                    except:
                        print("The packet needs to be resend")
                print(f"execute: {sizeWindow} -> {sizeWindow*2}")
                sizeWindow = sizeWindow * 2
                tempo = (time.time() - g_windowTime) * 1000
                print(f'{str(round(tempo, 2)).replace(".", ",")}; {int(sizeWindow)}')
                if tempo > 10000:
                    exit()


        def send_packets(sizeWindow, packets_sent, packets_resend, id_packet):
            global g_windowTime
            i = 0
            j = 0
            timer = 0

            while i < sizeWindow:

                if packets_resend == []:
                    packet = id_packet.encode('utf-8')
                    id_packet = str(int(id_packet) + 1)
                elif packets_resend != []:
                    packet = packets_resend.pop(0)

                if packet not in packets_sent:
                    packets_sent.append(packet)

                # Send the packet
                try:
                    sock.sendall(packet)
                except:
                    print("Problem with sendall")
                    connect()

                # Timer
                if (i == 0):
                    timer = time.time()
                elif (i > 0) and (time.time() > (timer + 0.01)):
                    if sizeWindow > 1:
                        j = i + 1
                        while j < sizeWindow:
                            packet = id_packet.encode('utf-8')
                            id_packet = str(int(id_packet) + 1)
                            packets_resend.append(packet)
                            j += 1
                        print(f"send packets: {sizeWindow} -> {sizeWindow/2}")
                        sizeWindow = sizeWindow / 2
                        currentTime = (time.time() - g_windowTime) * 1000
                        print(f'{str(round(currentTime, 2)).replace(".", ",")}; {int(sizeWindow)}')

                        send_packets(sizeWindow, packets_sent, packets_resend, id_packet)

                i += 1

            return sizeWindow, packets_sent, id_packet

        def connect():
            sock.Connect(server_address)

        execute()

        sock.close()

if __name__ == '__main__':
    server = Server()
    server.start()
    time.sleep(1)

    client = Client()
    client.start()

以下是相关输出:

Server starting up on 127.0.0.1 port 13000
Waiting a connection
Connection from  ('127.0.0.1', 53654)
Send packet returned: 1
execute: 1 -> 2
0,36; 2
Send packet returned: 2
execute: 2 -> 4
0,66; 4
Send packet returned: 4
execute: 4 -> 8
0,95; 8
Send packet returned: 8
execute: 8 -> 16
1,28; 16
Send packet returned: 16
execute: 16 -> 32
1,85; 32
Send packet returned: 32
execute: 32 -> 64
3,02; 64
Send packet returned: 64
execute: 64 -> 128
5,35; 128
Send packet returned: 128
execute: 128 -> 256
8,97; 256
Send packet returned: 256
execute: 256 -> 512
18,17; 512
send packets: 512 -> 256.0
28,84; 256
Send packet returned: 256.0
execute: 256.0 -> 512.0
38,54; 512
send packets: 512.0 -> 256.0
48,62; 256
Send packet returned: 256.0
execute: 256.0 -> 512.0
54,73; 512
Send packet returned: 512.0
execute: 512.0 -> 1024.0
61,23; 1024
send packets: 1024.0 -> 512.0
71,58; 512
Send packet returned: 512.0
execute: 512.0 -> 1024.0
81,75; 1024
send packets: 1024.0 -> 512.0
91,94; 512
send packets: 512.0 -> 256.0
102,01; 256
Send packet returned: 512.0
execute: 512.0 -> 1024.0
108,74; 1024

send_packets(递归调用两次)将sizeWindow除以4(从1024到512到256)时,execute方法获取的返回值是512而不是256。你知道吗

相关问题 更多 >

    热门问题