I recently started learning socket programming with python. Starting with the most basic scripts of server and client on the same computer, I wrote the following code.
Server.py
import socket
import time
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
serversocket.bind((host,port))
serversocket.listen(5)
while True:
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" %str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
Client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.connect((host,port))
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" %tm.decode('ascii'))
I'm using spyder IDE. Whenever I run the client in the IPython Console, this is what I get:
"ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it."
and whenever I run the Server I get an unending process.
So, what should I do to make this work?
Thank you for any help!
Credits :- http://www.bogotobogo.com/python/python_network_programming_server_client.php
Try changing socket.gethostname() to socket.gethostbyname(socket.gethostname()). gethostbyname returns the ip for the hostname. You want to setup a socket to connect to an ip, port. Alternatively, since you are running everything locally, just set your host to "127.0.0.1" directly for both the client/server.
Related
I know this was already asked but the previous questions didn't help. I'm trying to send some data using sockets. Specifically I'm using my laptop as server and a Linux emulator (Termux) on my smartphone as a client. Here below you can see the two Python codes. For the server:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
s.close()
And for the client:
import socket
HOST = ''
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
s.close()
When I'm connected to the same WiFi and in HOST (in both codes) I put the IP I see from ipconfig (192.168.---.---) everything works. It also works if in the HOST of the server I put 0.0.0.0.
However, when I put the IP of the machine (that I can see on https://whatismyipaddress.com/) and instead of using the WiFi I use the phone connection I get: ConnectionRefusedError: [Errno 111] Connection Refused.
Can someone explain me how can I connect client and server when the networks are different? I have been stuck with this for a while.
I also tried to open a port on the Firewall following this procedure and put it in the code instead of 5555 but still it didn't work.
Thank you in advance for the help.
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()
Just use a different port. Both the client and server should have the same port and host if not it won't work. Make sure to run the server before the client script.
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.
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(b"hello")
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 question's 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(b"hello")
It is important that this is b'hello' not is 'hello'
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.
so ive just started leaning about socketing when I came across an odd problem. I can make a connection between my Window computer and my Raspberry pi when the Pi is running my server script and my Windows running my client script, but when I try to run the server script on my Windows and client on my Pi they do not connect (after switching the host of course). Anyone have any idea why this is happening?
#server code
import socket
import time
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = '192.168.0.23'
port = 2613
serversocket.bind((host, port))
serversocket.listen(5)
while True:
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
and
#client code
import socket
clientsocket = socket.socket()
host = '192.168.0.23'
port = 2613
clientserver.connect((host,port))
print s.recv(1024)
clientserver.close
In your client code you have a clientsocket which you then call clientserver then call s. Both clientserver and s are undefined. Try:
#client code
import socket
clientsocket = socket.socket()
host = '192.168.0.23'
port = 2613
clientsocket.connect((host,port))
print (clientsocket.recv(1024))
clientsocket.close
Also try running the server script on Windows with Administrator privileges so it can open the port and check your firewall settings on Windows for port 2613.
I was learning about networking and I have some trouble understanding what went wrong.
I created a Client and a Server script:
Server:
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print ("Got connection from: " ,addr)
c.send("Thanks".encode('utf-8'))
# c.sendto(("Thank you for connection").encode('utf-8'), addr)
c.close()
and Client:
import socket
s=socket.socket()
host=socket.gethostname()
port = 12345
s.connect((host,port))
c=s.recv(1024)
print (c)
s.close
When I am trying to run from my computer I have no problem (both scripts)
But when I am running the Client from another Computer, the following error pops up for the Client: ConnectionRefuseError: WinError10061 No connection could be made because the target machine actively refused it.
Got any idea what could fix this?
The problem was that I wasn't referring to the server IP when running from another computer, I fixed it by passing the server IP, in the client script, like this host = "10.x.x.x"
Sorry for creating a useless question!
I've tried to connect two computers with a socket in Python and I don't know why it doesn't work. The files are from internet and it compiles for me but without any results.
The server.py:
#!/usr/bin/python
import socket
s = socket.socket()
host = ''
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
and the client.py:
#!/usr/bin/python
import socket
s = socket.socket()
host = # here I put the ip of the server's laptop
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close()
What's wrong?
You have to run the server first. Then run the client at the same time with the IP of the server (I used localhost because it was running on one computer, maybe you should try if that works). The code worked fine for me, every time I ran the client, the server printed a message. If it doesn't work for you, maybe your firewall is not letting you open ports.
Just for the future, please always post any error messages you see.
BTW, isn't this the Python Documentation example for sockets?