I try to print out this code and the command in Pycharm looks like as it was looping through the code and no result displayed, I said that because the terminal doesn't complete its task, and the dollar sign doesn't appear. I need to know if that code results in any output from it. this code is a copy of some tutorial hence it's not created by me.
import socket
HOST = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (HOST, PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(ADDR)
s.listen()
print('running')
conn, addr = s.accept()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ADDR)
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))
Also, I need to know what is the relationships between (WSGI, ASGI) and their relations with the socket in python.
The code following conn, addr = s.accept() never runs because s.accept is blocking. Move the client socket's code to a separate file and run it seperately.
Server code:
import socket
HOST = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (HOST, PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(ADDR)
s.listen()
print('running')
conn, addr = s.accept()
data = conn.recv(1024)
conn.close()
s.close()
print('Received', repr(data))
Client code:
import socket
HOST = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (HOST, PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ADDR)
s.sendall(b'Hello, world')
s.close()
Related
I have a simple socket server, how do I shut it down when I enter "shutdown" in the terminal on the server side?
import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
Close active connections and exit. It can be done with:
server.close()
exit(0)
To shutdown you socket server manually by calling server.close(), you whole code should be:
import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
# call server.close() to shut down your server.
trying to ping a server from a client like this:
#server
import socket
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
#client
import socket
HOST = ''
PORT = 50007
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print(f"Received {data!r}")
But there is a hang on server side after the s.accept(), and ...[111] connection refused on the client side.
BTW: I am on a windows machine for the server, and pinging from a linux machine. They are connected with an ethernet cable. I have also set a static address for the linux machine, from the windows machine.
Another thing, is that the exact same code works in the opposite direction ...
Could someone help?! Stuck on this for ages!
Note : This problem has been completely solved, as was am running client.py before server.py
Just got started with socket programming, I have created the below code and expecting to print some byte message, but it isn't doing that.
I just want to make the message available for any person on any
machine. But it's refusing by the machine to do that.
Here is my code:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12048
s.bind((socket.gethostname(), port))
s.listen()
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12048
s.connect(('192.168.0.1', port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Some images to better explain my errors:
Any help would be appreciated!!!
It looks like in the server.py script you use s.bind((socket.gethostname(), port)) where socket.gethostname() is a hostname, but in the client.py script you use s.connect(('192.168.0.1', port)) where '192.168.0.1' is the hostname you are trying to connect.
I think there you have socket.gethostname() != '192.168.0.1' and that's the problem.
Also, you can bind to all available IP addresses on the host using this solution Python socket bind to any IP?
Let's use listen_ip = socket.gethostbyname(socket.gethostname()) for connection since socket.gethostname() may return hostname instead of IP and it will not be solved by python dns resolver in local network if it was local name, not DNS.
and use it later as s.bind((listen_ip, port)) and s.connect((listen_ip, port))
After some debugging I've got a working solution for you
There are the scripts required.
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12_048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
# or we can set it using env variable named SERVER_IP
if 'SERVER_IP' in os.environ:
host = os.environ['SERVER_IP']
port = 12048
print("Connecting to {}:{}".format(host, port))
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
In a chat conversation we concluded that the hardcoded IP in the question is not the correct one. This solution does have the IP he needed but it will be different in each case. Remeber that server.py needs to be launched first, and when you see the printed Server listening # IP:12048, write that IP in client.py and launch it. Client does need to be launched after seeing that line even if you already know the IP, as the server needs some time to be ready and the client will crash if it tries to connect to the server while it is not ready.
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12048
s.bind((host, port))
s.listen()
print("Server listening # {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
port = 12048
print("Connecting to {}:{}".format(host, port))
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
A simple demo of socket programming in python:
server.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
print 'Received:', data
if not data:
break
conn.sendall(data)
print 'Sent:', data
conn.close()
client.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
print 'Received:', s.recv(1024)
s.close()
Now code work well. However, the client may not know if server will always send back every time. I tried symmetric code of while-loop in server.py
client_2.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
while True:
data = s.recv(1024)
if not data:
break
print 'Received:', data
s.close()
This code will block at
data = s.recv(1024)
But in server.py, if no data received, it will be blank string, and break from while-loop
Why it does not work for client? How can I do for same functionality without using timeout?
You can set a socket to non-blocking operation via socket.setblocking(false), which is equivalent to socket.settimeout(0). Solving this "without using timeout" is impossible.
Trying to create my first client-server application, I came across an error. This code is exactly the same as in the documentation, but I have problems.
Server:
import socket
HOST = 'localhost'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while True:
data = conn.recv(1024)
if not data: break
print data
conn.close()
Client:
import socket
HOST = 'localhost'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
s.close()
After execution, I don't see the message print Connected by, addr and print data in the server part.
I use Windows 7, Komodo Firewall (I tried to close the firewall, but it didn't solve the problem), Avast Antivirus, Python 2.7.
Very interesting, that there are no errors, but the output just doesn't work.
Also, my server application just freezes until the client connects to the server. Can this be solved just using threading?
Thanks in advance.
You need to accept() and print inside the loop. (or use two loops). I'm not very familiar with socket programming in Python but I'm guess it would look something like this. (completely untested!)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, addr = s.accept()
print 'Connected by', addr
while True:
data = conn.recv(1024)
if not data:
break
print data
conn.close()
+1 to Cfreak. Basically what is happening with data is that it is getting assigned an empty string which causes the loop to break. So putting the print statement in the loop fixes the problem. Assuming you need to access that data after the loop terminates try something like
data = []
while True:
datum = conn.recv(1024)
data.append(datum)
if not datum: break
print " ".join(data)
Here is the code I am running and my computer, and it works
client
import socket
HOST = 'localhost'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
s.close()
server
import socket
HOST = 'localhost'
PORT = 9090
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
data = []
while True:
datum = conn.recv(1024)
data.append(datum)
if not datum: break
print " ".join(data)
conn.close()
so I don't think it is a problem with your code... if you have a machine without a firewall/antivirus on it try the program on that machine.