简体   繁体   中英

nonstop server client connection[Python]

I want to create a server-client connection that the client can always be connected to the server. How can I do it? Please help me. when I was trying, this error occurred. "ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host"

- code -

server:

import socket
try:
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host,port))
    s.listen(1)
    conn, addr=s.accept()
    while True:
         conn.send(("Test message").encode())
         print((conn.recv(1024)).decode())
except Exception as error:
    print(str(error)) 

client:

import socket    
try:   
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((server_host,port))
    while True:

         print((s.recv(1024)).decode())
         s.send(("Test message").encode())
except Exception as error:
    print(str(error))  

Some reasons cause this error message:

  1. Server reused the connection because it has been idle for too long.
  2. May be Client IP address or Port number not same as Server.
  3. The network between server and client may be temporarily going down.
  4. Server not started at first.

Your code seems to be OK. Did you run the Server at first time then client? Please make sure it. The below code fully tested on my computer.

Server:

import socket

HOST = '127.0.0.1'  # (localhost)
PORT = 65432        # Port to listen on

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()

    while True:
        data = conn.recv(1024).decode()
        if not data:
            break
        conn.send(data.encode())

Client

import socket

HOST = '127.0.0.1'  # Server's IP address
PORT = 65432        # Server's port

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))

    while True:
        s.send(("Hi server, send me back this message please").encode())
        data = s.recv(1024).decode()
        print('(From Server) :', repr(data))

Note: Run the Server first then Client.

Output:

运行代码的输出

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