简体   繁体   中英

How to repeat TCP / IP communication in one function with Python?

I wrote the following TCP / IP code in Python.

client.py

import socket
from contextlib import closing

def send_msg():
    host = '127.0.0.1'
    port = 4000
    buf_size = 4096

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    with closing(sock):
        sock.connect((host, port))
        sock.send(b'hello world')
    return

send_msg()

server.py

import socket
from contextlib import closing

def run_server():
    host = '127.0.0.1'
    port = 4000
    backlog = 10
    buf_size = 4096
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    with closing(sock):
        sock.bind((host, port))
        sock.listen(backlog)
        while True:
            conn, address = sock.accept()
            with closing(conn):
                msg = conn.recv(buf_size)
                print(msg)
    return

run_server()

These codes worked fine.

But I don't want to execute send_msg () repeatedly.

Actually I want to write a while statement in the send_msg () function and repeat the transmission,like below code.

clientError.py

import socket
from contextlib import closing

def send_msg():
    host = '127.0.0.1'
    port = 4000
    buf_size = 4096

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    with closing(sock):
        sock.connect((host, port))
        while True:
            sock.send(b'hello world')
    return

send_msg()

However, clientError.py gives an error.

The details of the error are as follows.

"clientError.py", line 13, in send_msg
    sock.send(b'hello world')
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

How can I repeat send in one function?

I was able to repeat it by modifying the following server.py as follows.

Thank you,Ace shinigami.

import socket
from contextlib import closing

def run_server():
    host = '127.0.0.1'
    port = 4000
    backlog = 10
    buf_size = 4096
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    with closing(sock):
        sock.bind((host, port))
        sock.listen(backlog)
        while True:
            conn, address = sock.accept()
            with closing(conn):
                while True:
                    msg = conn.recv(buf_size)
                    print(msg)
    return

run_server()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM