Junior — Middle
Can you explain what a network socket is and how it is used in programming for data exchange over a network?
sobes.tech AI
Answer from AI
A network socket is a software object that provides bidirectional communication between two nodes in a network. It functions as an endpoint for sending and receiving data over TCP or UDP protocols.
In programming, sockets are used for data exchange between a client and a server. For example, a server creates a socket and 'listens' on a specific port, while a client connects to this port through its socket. Once the connection is established, they can exchange messages.
Example in Python (TCP server and client):
# Server
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)
conn, addr = server_socket.accept()
print('Connected by', addr)
data = conn.recv(1024)
conn.sendall(data)
conn.close()
# Client
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
client_socket.sendall(b'Hello, server')
data = client_socket.recv(1024)
print('Received', data)
client_socket.close()
Thus, sockets allow programs to exchange data over the network in real time.