I've read throught this introduction to python sockets: http://docs.python.org/3.3/howto/sockets.html
This is my server
import socket
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serversocket.bind(("localhost",8000))
serversocket.listen(5)
while True:
(client,addr)=serversocket.accept()
data=serversocket.recv(1024)
print(data.decode("utf-8"))
and this is the client
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost",8000))
The idea is that the server just prints all the data that was sent from the client. As you can see, I intended to encode the message strings as bytes with utf-8. But I never came that far.
With the server script running, I typed the client lines one by one into an IDLE python shell. After the third line, this error prompted up. Since I'm German, this is a vague translation. The error message will probably sound different if you can reproduce the error
Traceback (most recent call last): File "", line 1, in s.connect(("localhost",8000)) OSError: [WinError 10056] A connection attempt targeted an already connected socket.
How can I solve this error ? The server is slightly adapted, but the client is the exact code from the tutorial. And the error seens rather strange, after all I want the socket to be already connected - with the server . At first I thought that somehow there were already sockets connected to my server but restarting it and typing the client code again lead to the same result.
-
1i found a line duplicated,may this duplicated line is your problem: serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)pylover– pylover2013年05月14日 19:37:07 +00:00Commented May 14, 2013 at 19:37
-
thanks for your help. sadly the problem still persistslhk– lhk2013年05月14日 19:42:30 +00:00Commented May 14, 2013 at 19:42
-
1OSs are known for not wanting to close a socket until they are sure whatever was using them are really done. Put code in that will make sure they get closed properly on both sides. Even if the app crashes.cmd– cmd2013年05月14日 19:55:16 +00:00Commented May 14, 2013 at 19:55
2 Answers 2
You want to receive on the client socket, and close the client socket when the client closes. This will process one client at a time, but note it really needs a message protocol implemented to know it has a complete message to decode:
import socket
serversocket = socket.socket()
serversocket.bind(('',8000))
serversocket.listen(5)
while True:
client,addr = serversocket.accept()
while True:
data = client.recv(1024)
if not data: break
print(data.decode('utf8')) # Note this might not contain a complete UTF-8 character.
client.close()
Comments
You don't want to call recv() on the socket you call listen() and accept() on. Use the newly connected client instead.