Socket recv in Python 3 一遍又一遍地重复输入

Socket recv in Python 3 repeating input over and over

我知道它发送这么多的原因是我将 recv 设置为 1024 并且可以通过更改它来更改允许的数量,但是我只希望发送一个 Hello World。我试着搜索这个问题,但没有找到真正有用的东西。提前致谢!!

服务器:

#!/usr/bin/python
import socket
import sys


class Server:
    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            print("socket created")

    def bind(self, HOST, PORT):
        try:
            self.sock.bind((HOST, PORT))
        except socket.error as msg:
            print("Bind failed. Error Code : " +
                    str(msg[0]) + "Message " + msg[1])
            sys.exit()
        print("Socket bind complete")

    def main_loop(self):
        self.sock.listen(10)
        print("Socket now listening")
        while 1:
            conn, addr = self.sock.accept()
            print("Connected with " + addr[0] + ":" + str(addr[1]))
            data = conn.recv(1024)
            print(data)
        self.sock.close()

    def main(self):
        HOST = ''
        PORT = 8888
        self.bind(HOST, PORT)
        self.main_loop()


def main():
    server = Server()
    server.main()


if __name__ == "__main__":
    main()

客户

#!/usr/bin/python
import socket
import sys


class Client:
    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            print("socket created")

    def connect(self, HOST, PORT):
        try:
            self.sock.connect((HOST, PORT))
        except socket.error as msg:
            print("Connect failed. Error Code : " +
                    str(msg[0]) + "Message " + msg[1])
            sys.exit()
        print("Socket connect complete")

    def main_loop(self):
        while 1:
            self.sock.sendall(b'Hello world')
        self.sock.close()

    def main(self):
        HOST = ''
        PORT = 8888
       self.connect(HOST, PORT)
       self.main_loop()


def main():
    client = Client()
    client.main()


if __name__ == "__main__":
    main()

服务器输出:

socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:45676
b'Hello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello worldHello world'

客户端输出:

socket created
Socket connect complete

我怀疑问题出在客户端,而不是服务器:

def main_loop(self):
    while 1:
        self.sock.sendall(b'Hello world')
    self.sock.close()

当调用main_loop方法时,它会发送'Hello world'直到用户干预或进程死亡或计算机楔入或宇宙热寂,以先发生者为准。