tag: socket | Python Tutorial

Tag: socket

Socket Client

How do you open a network connection?

Sockets are the basis of any network communication in your computer.

If you open a website, a socket is created in the background. The same thing applies to chat applications or any other network application.

Related Courses

The TCP/IP model

Packets are delivered to another computer using a layered model: the TCP/IP model.

Every layer of the TCP/IP model has a certain purpose.

tcp/ip model

The application layers responsibility is solely the communication language between two applications.

Sockets work on the application protocol layer. Applications often have their own protocols, which in turn use sockets in the background.

If you want to make your own application protocol (chat system or other purposes) you can use sockets.

Note: This model is used in all network applications.

Python simple socket client

Make a socket application?

We will create a simple socket client, that mimics a webbrowser. The web uses port 80. The steps a webbrowser does to get a webpage are:

  • create socket
  • get server ip address from domain name
  • connect to server using ip address
  • send request to server
  • receive data (webpage)
    In code that will look like:
     # Socket client example in python

    import socket
    import sys

    host = 'www.pythonprogramminglanguage.com'
    port = 80 # web

    # create socket
    print('# Creating socket')
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error:
    print('Failed to create socket')

    print('# Getting remote IP address')
    remote_ip = socket.gethostbyname( host )
    except socket.gaierror:
    print('Hostname could not be resolved. Exiting')

    # Connect to remote server
    print('# Connecting to server, ' + host + ' (' + remote_ip + ')')
    s.connect((remote_ip , port))

    # Send data to remote server
    print('# Sending data to server')
    request = "GET / HTTP/1.0\r\n\r\n"

    except socket.error:
    print 'Send failed'

    # Receive data
    print('# Receive data from server')
    reply = s.recv(4096)

    print reply
    Of course all data returned will be shown as the raw html (no images, css etc).

Download network examples

Socket Server

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.

Related Courses

The Algorithm

Sockets work on the application layer, it does not specify any protocol and on this level you’d define an application protocol yourself.

Creation of a socket server needs these steps:

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.

import socket
import sys

HOST = ''
PORT = 7000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('# Socket created')

# Create socket on port
s.bind((HOST, 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[0] + ':' + str(addr[1]))

# Receive data from client
while True:
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 created
# Socket bind complete
# Socket now listening
# Connected to

Once running it will wait for messages. To connect with it, use telnet or modify the socket client from the previous section.