DEV Community

Cover image for Python sockets
natamacm
natamacm

Posted on

Python sockets

A socket lets you connect on the network byte level. The name in English comes from the electricity socket.

socket is Python module you can use to fiddle around with the network. It lets you connect to a server (or p2p node) and interact between the computers.

You can create a client or server at byte level, meaning you can implement your own protocols.

You can do this for a server too. This article is about the server side.

To start a server, it's as simple as (source)

#coding: utf8
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 1024))
s.listen(10)

conn, addr = s.accept()

r = conn.recv(1024)
print(r)

# s.send('hi client, this is greeting from server')

conn.close()
s.close()

You import the socket module, then define the port to listen on (1024), wait for connection and then communicate with the client.

A client can be an existing app (web browser, ftp client, telnet) but this depends on what protocol your server application supports.

Telnet can be used to test the server:

 telnet
telnet> o 127.0.0.1 1024
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
telnet> 

In this case the server is not running, otherwise you'd be able to run it. If you are implementing an existing protocol, it makes sense to test with existing software (client/server) to eliminate bugs that way.

Uncomment the line below to receive a message on the client.

# s.send('hi client, this is greeting from server')

If you want to connect more than one client, you need to use multi-threading. But for a simple test single threading is fine.

Top comments (0)