Create_server function of Python socket module

Overview:

  • 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:

# 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",
                                35491), 
                                family = socket.AF_INET6)
# Move to listen state
server.listen()

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

Client:

#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)
socketObject.sendall(bytes)

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

socketObject.close()

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 © pythontic.com