Jul 26, 2024
socket.socket()
socket.AF_INET
(for IPv4) or socket.AF_INET6
(for IPv6).socket.SOCK_STREAM
for TCP (connection-oriented).socket.SOCK_DGRAM
for UDP (connectionless).bind()
: Binds the host and port to a socket.listen()
: Starts the TCP listener.accept()
: Accepts incoming TCP connection requests.send()
: Sends a message over TCP.recv()
: Receives messages over TCP.close()
: Closes the socket connection.Set up Environment
server.py
in Visual Studio Code.Import the Socket Module
import socket
Create a Socket Object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Get Hostname and Bind
host = socket.gethostname()
server_socket.bind((host, port))
Listen for Connections
server_socket.listen(3) # maximum 3 connections
Accept Connections in a Loop
while True:
client_socket, address = server_socket.accept()
print(f'Connection received from {address}')
```
Send Message to Client
message = 'Thank you for connecting to the server!'
client_socket.send(message.encode())
Close Client Socket
client_socket.close()