Create_connection() In Python

Function Name:

create_connection

 

Function signature:

socket.create_connection(address[, timeout[, source_address]])

 

Function Overview:

  • create_connection() function only connects to a TCP socket and it cannot be used to connect to a Datagram socket or any other type.
  • This function is like a specialized wrapper over the socket.connect() function.
  • The address parameter of this function takes IPv4 , IPv6 addresses as well as host names. Remember that, you cannot connect to a server socket that was created using the address family AF_INET by passing an IPv6 address to create_connection().
  • To use create_connection() to connect to a IPv6 address the server socket also should have been created using the address family AF_INET6.

Parameters:

address: The destination address to which the socket wants to connect to. The address is a tuple of IP address and a port.

timeout: Timeout value in seconds. When not specified it takes the timeout value as returned by the method socket.getdefaulttimeout()

source_address: Timeout value in seconds

Example:

# Sample program for CreateConnection

 

import socket

 

# Create a socket to be used a client

socket.setdefaulttimeout(10)

timeout = socket.getdefaulttimeout()

print("System has default timeout of {} for create_connection".format(timeout))

socketInstance = socket.create_connection(("localhost",35491))

 

bytes2Send       = str.encode("Hello server system!")

socketInstance.sendall(bytes2Send)

 

# Receive the data

while(True):

    data = socketInstance.recv(1024)

    print(data)

 

    if(data==b''):

        print("Connection closed")

        break

 

socketInstance.close()

 

  • The above python program uses create_connection() to connect to the TCP server socket listed in the client-server example. The TCP server code has been modified so that the server socket is created using address family AF_INET6 and binds to the IPv6 address ::1 and port number 35491.
  • Using sendall() it sends a message to the TCP server
  • It receives the messages sent by the server in a while loop till the server socket closes the client connection and prints the messages to the console.

Output:

System has default timeout of 10.0 for create_connection

b'Hi Client! Read everything you sent'

b'Now I will close your connection'

b''

Connection closed

 


Copyright 2018 © pythontic.com