Socket Server (Network)

A server can be created using sockets. 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

Related Courses

Example socket server

import socket
import sys
 
HOST = ''  
PORT = 7000
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('# Socket created')
 
# Create socket on port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print('# Bind failed. ')
    sys.exit()
     
print('# Socket bind complete')
 
# Start listening on socket
s.listen(10)
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 )     
     
s.close()

Once run, a server will be running on localhost port 7000.

# Socket created
# 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.

Python Socket Client (Network)
Get links from webpage

4 thoughts on “Socket Server (Network)

  1. Reply
    Jules - October 17, 2016

    Would the “while True” block not execute indefinitely? Would s.close() statement ever be executed? Would this script ever listen for a new client ever again with “conn, addr = s.accept()” being outside the loop?

    1. Reply
      admin - January 19, 2017

      Yes, while True executes indefinitely. Instead could wait for an exit message or input

  2. Reply
    gopy - March 7, 2017

    what should i do in order to send an http response (html code), which includes photos. so that i can get or download the image from other pc.

    1. Reply
      admin - May 15, 2017

      upload the photo to a server and attach a link in the html response. You can also include it in binary, but think a link is a better way.

Leave a Reply

Your email address will not be published. Required fields are marked *