Reputation: 125
My socket sends the first message but nothing afterward.
The output in the server:
What do you want to send?
lol
The client receives:
From localhost got message:
lol
And then it doesn't want to send anything else.
I don't get the what do you want to send
printed anymore.
My code:
server.py
file:
#!/usr/bin/python3
import socket
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
print ("got host name:", host)
port = 9996
print("connecting on port:", port)
# bind to the port
serversocket.bind((host, port))
print("binding host and port")
# queue up to 5 requests
serversocket.listen(5)
print("Waiting for connection")
while True:
clientsocket, addr = serversocket.accept()
msg = input("what do you want to send?\n")
clientsocket.send(msg.encode('ascii'))
client.py
file:
#!/usr/bin/python3
import socket # create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine
# name
host = socket.gethostname()
port = 9996 # connection to hostname on the port.
s.connect((host, port)) # Receive no more than 1024 bytes
while True:
msg = s.recv(1024)
print(msg.decode("ascii"))
Upvotes: 2
Views: 1547
Reputation: 78690
The client only connects once (OK) but the server waits for an incoming connection every start of the while
loop.
Since there are no more connection requests by a client, the server will freeze on the second iteration.
If you just want to handle a single client, move clientsocket, addr = serversocket.accept()
before the while
loop. If you want to handle multiple clients, the standard way is to have the server accept connections inside the while
loop and spawn a thread for each client.
You can also use coroutines, but that may be a bit overkill if you are just starting out.
Upvotes: 1