TCP只能发送第一条消息

时间:2021-04-25 13:07:02

标签: python sockets tcp

我制作客户端服务器应用程序。它看起来像这样:

客户

import socket
host = '127.0.0.1'
port = 1338
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

while True:
    st = input("Your message: ")
    byt = st.encode()
    s.send(byt)

服务器

import socket
host = ''
port = 1338
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
while True:
    s.listen(5)
    conn, addr = s.accept()
    data = conn.recv(2000)
    print(data.decode())

问题是只显示第一条消息。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

由于客户端的 connect 在循环之外,因此您必须将服务器的 listenaccept 也放在循环之外,因为连接只建立一次。< /p>

答案 1 :(得分:0)

服务器在接受来自客户端的连接后只接收一次数据。为了连续接收,你可以有一个while循环来接收来自客户端的数据。

<!-- https://svgpocketguide.com/book/#section-4 -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" width="1080" height="1080">
    <!-- the doctype and svg need to be like this to render in Firefox -->
    <rect width="1080" height="1080" fill="white"/>

<!-- delay frames by waiting 0.5 seconds between frames -->

    <animation frame 1>
        <line x1="75" y1="75" x2="10" y2="50" stroke="hsl(0,82%,56%)" stroke-width="3"/>
        <line x1="75" y1="75" x2="175" y2="475" stroke="hsl(236,82%,56%)" stroke-width="3"/>
        <circle cx="10" cy="50" r="5" fill="black" />
        <circle cx="75" cy="75" r="5" fill="black" />
        <circle cx="175" cy="475" r="5" fill="black" />
    </animation frame 1>

    <animation frame 2>
        <line x1="75" y1="75" x2="10" y2="50" stroke="hsl(0,82%,56%)" stroke-width="3"/>
        <line x1="75" y1="75" x2="175" y2="475" stroke="hsl(236,82%,56%)" stroke-width="3"/>
        <circle cx="10" cy="50" r="5" fill="black" />
        <circle cx="75" cy="75" r="5" fill="black" />
        <circle cx="175" cy="475" r="5" fill="black" />
    </animation frame 2>

</svg>

所以,只要用户提供数据,上面的代码就会接收数据。您也可以将数据接收部分分离在一个单独的线程中。