DEV Community

Cover image for python server socket
tcs224
tcs224

Posted on

python server socket

In Python you can do network programming. You may be familiar with network programming at high level (the web, ftp).

This uses the client-server model, where the server sends the data (web, ftp) and the client is your computer. Upon typing the website url, the web data is returned from the web server.

On the web, every web browser is a client and every website runs on a server. Typically there are many web browsers connecting to the same server (website).

cient server

But did you know you can program low-level and create your own protocols?

Welcome to the world of sockets. You can use sockets to create your own server or client. Before playing with Python, you should know the basics of Python

Socket server

Lets create your own socket server. You can do this by following a few steps:

  • import sockets
  • define host and port
  • wait for client
  • parse client data (and send)

First import the sockets module:

import socket

Then define the host and port

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port

Open the server and wait for a client:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr

Then you can wait for data (or send data) and parse it according to your protocol. Data could be in plain text, json, xml or any other format. If you are implementing an existing protocol, you should use the one defined.

while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

That's all there is to it to startup a server. Make sure your firewall isn't blocking the server and that you have the user permissions to open a server.

Telnet client

If your server is running, open a new terminal. In the new terminal you can use telnet to connect to the server

telnet 127.0.0.1 50007

Where 127.0.0.1 is your computer (loopback ip) and 50007 is the port you opened in the server program. Once connected try to send some data and take a look at your server terminal. If you need to, you can also create a socket client in Python.

Related links:

Top comments (0)