import socket # create a socket object server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to a public host and a well-known port server_socket.bind(('localhost', 1234)) # listen for incoming connections server_socket.listen(5) # wait for a client connection request and accept it client_socket, address = server_socket.accept() # print the client address print("Connection from", address) # close the connection client_socket.close()
import socket # create a socket object client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to a remote server client_socket.connect(('localhost', 1234)) # send a message to the server client_socket.send(b'Hello, server!') # receive a response from the server data = client_socket.recv(1024) # print the response print(data.decode()) # close the connection client_socket.close()In this example, we create a client socket object and connect it to a remote server. We then send a message to the server using the socket send method and receive the response using the socket recv method. Finally, we print the response and close the client socket object. The socket module is a built-in package library in Python, so no additional installation is required.