Do you want to make a socket server app?
A server can be created using the module socket.
If you make a socket server, you can define your own application protocol. You can also use it to work with existing apps.
- Complete Python Bootcamp: Go from zero to hero in Python
- Python for Network Engineers: Netmiko, NAPALM, pyntc, Telnet
Sockets work on the application layer, it does not specify any protocol and on this level you’d define an application protocol yourself.
- bind socket to port
- start listening
- wait for client
- receive data
Example socket server
The example below starts a socket server on port 7000. You can use telnet or a socket client to connect to this port.
HOST = ''
PORT = 7000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('# Socket created')
# Create socket on port
except socket.error as msg:
print('# Bind failed. ')
print('# Socket bind complete')
# Start listening on socket
print('# Socket now listening')
# Wait for client
conn, addr = s.accept()
print('# Connected to ' + addr + ':' + str(addr))
# Receive data from client
data = conn.recv(1024)
line = data.decode('UTF-8') # convert to string (Python 3 only)
line = line.replace("\n","") # remove newline character
print( line )
Once run, a server will be running on localhost port 7000.
# Socket bind complete
# Socket now listening
# Connected to 127.0.0.1:40499
Once running it will wait for messages. To connect with it, use telnet or modify the socket client from the previous section.