python socket programming : error trying to connect to server - python

I'm a beginner in python socket programming and I have to send a message from the server to the client side . I have 2 python IDLES one for the server and one for the client. I have made the server file with no errors but when I create a connection socket in my client file and try to connect to server I get the error:
clientSocket.connect((servername,port))
ConnectionRefusedError: [WinError 10061] no connection could be made because the target machine actively refused it
I don't know how to deal with this error and I would appreciate your help with guiding me.
Thank you in advance.
My code:
Server:
from socket import *
port = 1234
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',port))
serverSocket.listen()
print("Server has started")
data = "Network labs"
while True:
connectionSocket , addr = serverSocket.accept()
connectionSocket.send(data)
connectionSocket.close()
Client:
from socket import *
port = 1234
servername = 'localhost'
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((servername,port)) #this is where the error happens

I would gradually try to understand where the problem is coming from.
Try to identify where the problem is:
Write an example which is available online and will surely works, and then you will know that the problem is in your code.
Try to use the same code on different computer, or a VM. If it will work there you will know that the problem is with the environment.
Try to find people with similar problems, you will usually won't be the first. - Errno 10061 : No connection could be made because the target machine actively refused it ( client - server ) - this seems nice.
Find out if your server is running correctly, checks if someone is listening on port 1234 before running the client. (Use netstat)
Few things which unrelated to the subject but will improve your coding:
1. Don't import *, it's just an easy way to get name collision.
2. Use conventions, it's just make everything nicer to read. https://www.python.org/dev/peps/pep-0008/
Of course you can ignore all of this, it's just an advice.

Related

Python & Mcpi (minecraft) - connection refused error

I use mcpi: https://github.com/AdventuresInMinecraft/AdventuresInMinecraft-Linux
Starting the local server.
After, run program:
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
mc.postToChat("Hello Minecraft World")
I am facing the below error:
Traceback (most recent call last):
File "/home/home/AdventuresInMinecraft/MyAdventures/HelloMinecraftWorld.py", line 2, in mc = minecraft.Minecraft.create()
File "/home/home/.local/lib/python3.6/site-packages/mcpi/minecraft.py", line 376, in create return Minecraft(Connection(address, port))
File "/home/home/.local/lib/python3.6/site-packages/mcpi/connection.py", line 17, in init self.socket.connect((address, port))
ConnectionRefusedError: [Errno 111] Connection refused
A ConnectionRefusedError means that the address + port combination was unable to be secured for this particular Minecraft server and thus raised an exception. This could be because some other application is already using the port of interest, the port is unavailable because of the OS, or a handful of other networking configuration mishaps.
But perhaps a better series of questions to ask yourself is:
What is the default address and port that minecraft.Minecraft.create() will attempt to launch / listen at?
Do I have access to that server (address + port)?
If I do have access, are there any security issues (AKA Firewall)?
This post has already addressed the root issue of your question, and I hope it gives you a good start at understanding the foundation of your problem.
Notice how their question mentions s.connect((host,port)) and your stack trace has self.socket.connect((address, port)) Looks like the same thing to me!
Some more reading:
- localhost
- check if port is in use
I encountered the same issue. I looked into the code of mcpi and found that the default port is 4711. However, a Minecraft Server's default port is 25565. All you need to do is add 2 parameters on the create() function. Code(Python):
mc = minecraft.Minecraft.create(address="127.0.0.1", port=25565)
btw change "address" in the code to the host of the server (only if you modified the "server.properties" file).
Also, ConnectionRefusedError doesn't mean that it's not secured, I believe it means that either the server is not online, it doesn't exist, or the server refused it for some reason.
EDIT:
Oops sorry I just found out that mcpi actually connects to the RaspberryJam plugin which is hosted on another IP and port. The plugin runs on port 4711. So mcpi has the right port.
So check if you have the RaspberryJam plugin installed. If not, download it from
https://www.spigotmc.org/resources/raspberryjuice.22724/
And put the .jar file inside the plugins folder in your server directory.

Python client can not communicate with ruby server. I get [Errno 10061] No connection could be made because the target machine actively refused it

I have the intention of running machine learning algorithms written in Python on data in a database of a Ruby on Rails app. After some research I have discovered sockets and therefore created a Ruby server and Python client. I am running them both on two different command prompt terminals.
Here is the Ruby server code:
require "socket"
server = TCPServer.open(2000)
loop {
client = server.accept
client.puts(Time.now.ctime)
client.puts "Closing the connection. Bye!"
client.close
}
Here is the Python client code:
import socket
s = socket.socket()
host = "localhost"
port = 2000
s.connect((host , port))
I do not understand where the problem is. Kindly assist.
Given insightful answers to my question above the code Ruby server and Python client should be as below.
For the Ruby server:
require "socket" # Get sockets from stdlib
server = TCPServer.open("127.0.0.1" , 2000) # Socket to listen on port 2000
loop { # Server runs forever
client = server.accept # Wait for a client to connect
client.puts(Time.now.ctime) # Send the time to the client
client.puts "Closing the connection. Bye!"
client.close # Disconnect from the client
}
For the Python client:
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "127.0.0.1"
port = 2000 # Reserve a port for your service.
s.connect((host , port))
print s.recv(1024)
s.close() # Close the socket when done
The open() method of the TCPServer class in Ruby takes two parameters. The first being the host name and the second the port i.e
TCPServer.open(hostname , port)

library socket: open port

I have try to create a little online game with python but I face a problem.
I have no problem as long as I work in local (same computer or private IP adresse) but the socket can't connect if i use an IP.
Server:
import socket
co_prin = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
co_prin.bind(('', 9000))
co_prin.listen(10)
co,info=co_prin.accept()
print('connexion recu')
co.close()
co_prin.close()
Client:
import socket
co_serv=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
adresse='81.56.76.61'
co_serv.connect((adresse, 9000))
print("Connecté.")
co_serv.close()
If I change adresse by 'localhost' there is no problem.
One tell me that the reason was python can't open the port. I would like to know if there is a solution to solve or bypass the problem easy to use for other user. (I can always create a local network with hamachi or open the port manually but it's wouldn't be easy to share my programm).
Edit, the error in the client code: Traceback (most recent call last):
File "", line 5, in
co_serv.connect((adresse, 9000))
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it
You are not using your actual computer IP. You are using your public IP address.
Open cmd/command.com and type in the command: ipconfig.
You will there see a totally different IP (IPv4/IPv6 address):
Most likely you want this (do this for yourself!):
Then, if you want people outside your network want to access your computer you must port forward the port to your network IP address from your router.
If you are just experimenting with python, it's best to use 127.0.0.1 or localhost as IP-address.

connection refused from server unit I reset client machine

Below is the code I am running within a service. For the most part the script runs fine for days/weeks until the script hiccups and crashes. I am not so worried about the crashing part as I can resolve the cause from the error logs an patch appropriately. The issue I am facing is that sometimes when the service restarts and tries to connect to the server again, it gets a (10061, 'Connection refused') error, so that the service is unable to start up again. The bizarre part is that there is no python processes running when connections are being refused. IE no process with image name "pythonw.exe" or "pythonservice.exe." It should be noted that I am unable to connect to the server with any other machine as well until I reset computer which runs the client script. The client machine is running python 2.7 on a windows server 2003 OS. It should also be noted that the server is coded on a piece of hardware of which I do not have access to the code.
try:
EthernetConfig = ConfigParser()
EthernetConfig.read('Ethernet.conf')
HOST = EthernetConfig.get("TCP_SERVER", "HOST").strip()
PORT = EthernetConfig.getint("TCP_SERVER", "PORT")
lp = LineParser()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
reader = s.makefile("rb")
while(self.run == True):
line = reader.readline()
if line:
line = line.strip()
lp.parse(line)
except:
servicemanager.LogErrorMsg(traceback.format_exc()) # if error print it to event log
s.shutdown(2)
s.close()
os._exit(-1)
Connection refused is an error meaning that the program on the other side of the connection is not accepting your connection attempt. Most probably it hasn't noticed you crashing, and hasn't closed its connection.
What you can do is simply sleep a little while (30-60 seconds) and try again, and do this in a loop and hope the other end notices that the connection in broken so it can accept new connections again.
Turns out that Network Admin had the port closed that I was trying to connect to. It is open for one IP which belongs to the server. Problem is that the server has two network cards with two separate IP's. Issue is now resolved.

How to connect a Python socket on client-side to Node.js/socket.io?

I want to connect Blender (v2.55) to a webpage through sockets.
For the web part, I can use Node.js & socket.io. I've already used a little node.js/socket.io, it's not a problem I think.
Now for Blender, it runs on Python 3.1, so I've already sockets and I can add libraries if needed. I'm new to Python sockets, can I connect a client to node.js/socket.io directly ?
I tried with the basic code from the Python doc:
import socket
import sys
HOST, PORT = "127.0.0.1", 8080
data = "Hello from Blender"
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server and send data
sock.connect((HOST, PORT))
sock.send(bytes(data + "\n","utf8"))
# Receive data from the server and shut down
received = sock.recv(1024)
sock.close()
print("Sent: %s" % data)
print("Received: %s" % received)
It results by:
Sent: Hello from Blender
Received: b''
It seems that Blender is connected, but doesn't receive data. Also Node shows no new client connected…
Do I need something else ? If somebody can help me out…
You are missing a protocol/handshake. What you have there is a bare TCP socket connection. node.js/socket.io lives on top of a TCP socket. Basically when you open a connection to a socket.io server, it's expecting you to use some protocol for communication (websockets, longpolling, htmlfile, whatever). The initial handshake defines what that protocol will be. Websockets is one of the supported protocols. This blog post should help you. It doesn't look all that hard to get websockets implemented.
you can try the form of loop to receive valid data.
import socket
host="127.0.0.1"
port=8088
web=socket.socket()
web.bind((host,port))
web.listen(5)
print("recycle")
while True:
conn,addr=web.accept()
data=conn.recv(8)
print(data)
conn.sendall(b'HTTP/1.1 200 OK\r\n\r\nHello world')
conn.close()
and use your browser to visit the host and port for a check
I understand this thread is extremely old. But I faced the same problem recently and couldn't find an answer or any similar questions. So here is my answer.
Answer: Use socket.io for python python-socketio
The reason why built-in sockets or any other websocket library in python won't work is explained in the socket.io website socket.io
Socketio is simply just not a websoket connection. Although they say, it uses websockets for transport internally, the connection is established with HTTP protocol http:// as opposed to the WEBSOCKET protocol ws://. This results in the failure of handshake and the connection fails to be established.

Categories