Python Socket Programming – ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

Python Socket Programming – ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

For client.py

import socket
host = 127.0.0.1
port = 9879
buffer_size = 1024
text = Hello, World!
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
text = text.encode(utf-8)
s.send(text)
data = s.recv(buffer_size)
s.close()
print(received data:, data)

For server.py

import socket
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
buffer_size = 1024
text = Hello, World!
mysocket.bind((127.0.0.1, 9879))
mysocket.listen(5)
(client, (ip,port)) = mysocket.accept()
print(client, port)
client.send(bknock knock knock, Im the server)
data = client.recv(buffer_size)
print(data.decode())
mysocket.close()

Just change the port number and it will work and if you are in python3 then you will have to encode and decode as socket recieves and sends only binary strings.

I was following a tutorial that used threading to start the server. Once I removed the threading then I was able to connect to it.

Python Socket Programming – ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

I have succeed in my server!

My server python script is below:

    import socket
    host=0.0.0.0
    port=2345
    s=socket.socket()
    s.bind((host,port))
    s.listen(2)
    while True:
    conn,addr=s.accept()
    print(Connected by,addr)
    data=conn.recv(1024)
    print(received data:,data)
    conn.send(data)
    conn.close()

My Client python script is below:

import socket
s=socket.socket()
host=xx.xx.xx.xx       #This is your Server IP!
port=2345
s.connect((host,port))
s.send(bhello)
rece=s.recv(1024)
print(Received,rece)
s.close()

There is two points needed to be careful in the script:

1.The host of the Server must is

0.0.0.0

So that the python script could user all interfaces in the server

2.I have find the questions error through the prompt:

TypeError: a bytes-like object is required, not str

It means every string message in the send method need to convert to bytes-like object,So the correct is

s.send(bhello)

It is important that this is bhello not is hello

Leave a Reply

Your email address will not be published. Required fields are marked *