I'm trying to create a very basic server in python that listens in on a port, creates a TCP connection when a client tries to connect, receives data, sends something back, then listens again (and repeats the process indefinitely). This is what I have so far:
from socket import * serverName = "localhost" serverPort = 4444 BUFFER_SIZE = 1024 s = socket(AF_INET, SOCK_STREAM) s.bind((serverName, serverPort)) s.listen(1) print "Server is ready to receive data..." while 1: newConnection, client = s.accept() msg = newConnection.recv(BUFFER_SIZE) print msg newConnection.send("hello world") newConnection.close()
Sometimes this seems to work perfectly well (if I point my browser to "localhost:4444" the server prints out the HTTP GET request and the webpage print the text "hello world"). But I'm getting the following error message sporadically when I try to start the server after closing it in the last few minutes:
Traceback (most recent call last): File "path\server.py", line 8, in <module> s.bind((serverName, serverPort)) File "C:\Python27\lib\socket.py", line 224, in meth return getattr(self._sock,name)(*args) error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
I'm programming in python using Windows 7. Any ideas on how to fix this?
You're going to create a socket object using socket. socket() , specifying the socket type as socket. SOCK_STREAM . When you do that, the default protocol that's used is the Transmission Control Protocol (TCP).
You can send and receive on the same socket at the same time (via multiple threads). But the send and receive may not actually occur simultaneously, since one operation may block the other from starting until it's done.
Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection.
On Windows, you can try these steps:
# 4444 is your port number netstat -ano|findstr 4444
you will get something like this:
# 19088 is the PID of the process TCP 0.0.0.0:4444 *:* 19088
With:
tskill 19088
Or:
taskkill /F /PID 19088
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With