Search code examples
pythonsocketstcp

python socket return ConnectionRefusedError: [Errno 111] Connection refused


i am programming a chat room project by python.Below is my server.py and client.py .When client is trying to connect to server ,it returns"in line8, client.connect((ip,port)) ConnectionRefusedError: [Errno 111] Connection refused".I have no idea why client canʼt connect to server while telnet can do so without a error.If you have any idea,please let me know,thank you.

server.py

import socket
#ip =socket.gethostbyname(socket.gethostname())
ip="127.0.0.1"
port=8000
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((ip,port))
print("server ip address:"+ip)
server.listen(1)
conn,addr=server.accept()

user=addr[0]
print("[system]",user,"is online")
while True:
    message=str(conn.recv(1024), encoding='utf-8')
    if(not "quit()" in message):
        print(user+' : '+message)
    else:
        print("[system]"+user+" quit")
        conn.close()
        break

client.py

import socket


ip="127.0.0.1"
port=8000

client=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((ip,port))


while(1):
    message=input("input:")
    
    client.sendall(message.encode())
    if(message=="quit()"):
        break
client.close()

Solution

  • Approach 1 : Coroutines and Tasks

    Coroutines declared with the async/await syntax is the preferred way of writing asyncio applications.

    A running example:

    import asyncio
    
    
    async def f1():
        print('Hello')
        await asyncio.sleep(1)
    
    
    async def f2():
        print('World')
        await asyncio.sleep(1)
    
    asyncio.run(f1())
    asyncio.run(f2())
    

    Approach 2 : threading

    from time import sleep
    
    
    def f1():
        print('Hello ')
        sleep(1)
    
    
    def f2():
        print('World')
        sleep(1)
    
    
    Thread(target=f1).start()
    Thread(target=f2).start()
    

    Unfortunately, due to the Global interpreter lock the functions will not be truly executed in parallel:

    A global interpreter lock (GIL) is a mechanism used in computer-language interpreters to synchronize the execution of threads so that only one native thread can execute at a time. An interpreter that uses GIL always allows exactly one thread to execute at a time, even if run on a multi-core processor.

    Approach 3: multiprocessing

    multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine.

    from multiprocessing import Process
    from time import sleep
    
    
    def f1():
        print('Hello ')
        sleep(1)
    
    
    def f2():
        print('World')
        sleep(1)
    
    
    p1 = Process(target=f1)
    p1.start()
    p2 = Process(target=f2)
    p2.start()
    p1.join()
    p2.join()