Create_server Function Of Python Socket Module


  • Making a TCP server involves a four-step process of making calls to the create(), bind(), listen() and accept() functions of the socket module. 
  • The function create_server() wraps the first two steps of this process into a single call.
  • Creation of the server socket can be using an IPv4 address or an IPV6 address as specified by the argument family.
  • The accepted client connections can be both IPv4 based and IPv6 based or just IPv4 based. 


# Example Python program that uses 
# the socket.create_server() function to
# create a socket
import socket

# Create a socket and bind to the IP, port
server = socket.create_server(("2402:e280:215d:21b:8542:99d7:4400:8f07",
                                family = socket.AF_INET6)
# Move to listen state

# Serve to connection requests
print("Server starts to accept connections from clients...")
    serveOn = server.accept()
    print("Connection accepted...client details:",serveOn[1])
    msg = "hi"
    print("Message received:%s"%clientMsg.decode())
    print("Sending greetings to client")
    print("Connection to client closed")


#Example Python program that creates a clitn socket
#using the address family AF_INET6
import socket
# Create a socket
socketObject = socket.socket(family=socket.AF_INET6)

# Connect to the server
socketObject.connect(("2402:e280:215d:21b:8542:99d7:4400:8f07", 35491))
print("Connected to server")
# Send a hello
msg     = "Hello!"
bytes   = str.encode(msg)

# Receive the data
data = socketObject.recv(1024)
print("Server said:%s"%data.decode())


Server output:

Server starts to accept connections from clients...

Connection accepted...client details: ('2402:e280:215d:21b:81f7:4515:f9ab:ebd8', 61270, 0, 0)

Message received:Hello!

Sending greetings to client

Connection to client closed

Client output:

Connected to server

Server said:hi


Copyright 2024 ©