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

clientpythonsockets

I'm doing an assignment regarding socket programming in python using a client and server. I'm currently on windows 10. Before getting into the little details of the assignment, I've been trying to simply connect the server and client.

Every time I try to run the client file, I would get this error

File "tcpclient.py", line 9, in <module>
    s.connect((host, port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

I have opened the firewall ports and still nothing. I've tried replacing host with '', 0.0.0.0, socket.gethostname() in both the client and server file but the error still persists. I've even tried different port numbers but it made no difference. I've tried running this code on Ubuntu and Max and I get the same error – connection refused. I've been researching for many solutions but I still have yet to find one that works. Any help would be greatly appreciated!

Note: this code was taken online but it's essentially the basis of what I need to accomplish.
tcpclient.py

import socket

host = '127.0.0.1'
port = 80
buffer_size = 1024
text = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(text)
data = s.recv(buffer_size)
s.close()

print("received data:", data)

tcpserver.py

import socket

host = '127.0.0.1'
port = 80
buffer_size = 20  

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
    data = conn.recv(buffer_size)
if not data: break
print("received data:", data)
conn.send(data)  # echo
conn.close()

Best Answer

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(b"knock knock knock, I'm 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.

Related Topic