Saturday, December 31, 2022

How to create sockets in python

 In Python, you can use the socket module to create sockets (communication channels) for sending and receiving data over a network.

Here is an example of how to create a socket in Python:

import socket # create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() # reserve a port for your service port = 9999 # bind the socket to a public host, and a port s.bind((host, port)) # become a server socket s.listen(5) # establish a connection conn, addr = s.accept() print('Connected by', addr) # close the connection conn.close()

In this example, we use the socket() function to create a socket object. The first argument specifies the address family (AF_INET for IPv4) and the second argument specifies the type of socket (SOCK_STREAM for a TCP socket).

Then, we use the bind() function to bind the socket to a host and port. The listen() function tells the socket to start listening for incoming connections.

Finally, the accept() function waits for an incoming connection and returns a tuple containing the connection object and the address of the client.

Once a connection is established, you can send and receive data using the connection object's send() and recv() methods.

# send data conn.send(b'Hello, World!') # receive data data = conn.