xxxxxxxxxx
import socket
# Creating a socket server
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_host = 'localhost' # Host of the server (can be IP address or domain)
server_port = 9999 # Port number for the server to listen on
# Binding the socket server to host and port
server_socket.bind((server_host, server_port))
# Listening for incoming connections
server_socket.listen(1) # Allowing only one connection at a time
print(f'Server listening on {server_host}:{server_port} ...')
while True:
# Accepting a client connection
client_socket, client_address = server_socket.accept()
print(f'Accepted connection from {client_address}')
# Receiving data from the client
data = client_socket.recv(1024).decode()
print(f'Received data: {data}')
# Sending a response back to the client
response = 'Hello from the server!'
client_socket.send(response.encode())
# Closing the client connection
client_socket.close()
xxxxxxxxxx
#server.py:
import socket # Importing the socket module to create network sockets
# Defining the host and port to listen on
HOST = '127.0.0.1' # Localhost IP address
PORT = '8080' # Port number to listen on
# Creating a socket object for the server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Binding the socket object to the host and port
server.bind((HOST, int(PORT)))
# Listening for incoming connections from clients, with a maximum queue of 5 clients
server.listen(5)
# Infinite loop to keep the server running
while True:
# Accepting incoming connection from client and getting the communication socket and client address
communication_socket, address = server.accept()
print(f"connected to {address}")
# Receiving data from the client and decoding it to a string using UTF-8 encoding
message = communication_socket.recv(1024).decode('utf-8')
print(f"message: {message}")
# Sending a message back to the client to acknowledge that the message was received
communication_socket.send(f"message received".encode('utf-8'))
# Closing the communication socket with the client
communication_socket.close()
print(f"communication with {address} ended")
################################################################################
#client.py:
import socket # Importing the socket module to create network sockets
# Defining the host and port to connect to
HOST = '127.0.0.1' # Localhost IP address
PORT = '8080' # Port number to connect to
# Creating a socket object for the client
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connecting to the server at the specified host and port
client_socket.connect((HOST, int(PORT)))
# Sending a message to the server by encoding a string to bytes using UTF-8 encoding and sending it through the socket
client_socket.send("Hello world!".encode('utf-8'))
# Receiving a response from the server by receiving up to 1024 bytes of data through the socket and decoding it to a string using UTF-8 encoding
print(client_socket.recv(1024))
# Closing the socket connection with the server
client_socket.close()
xxxxxxxxxx
"""
UDP echo server that converts a message
received from client into uppercase and
then sends it back to client.
"""
from socket import *
# Port number of server
server_port = 12000
# Server using IPv4 and UDP socket
server_socket = socket(AF_INET, SOCK_DGRAM)
# Bind server to port number and IP address
server_socket.bind(("127.0.0.1", server_port))
print("The server is ready to receive msg...")
while True:
# Extract message and client address from received msg
message, client_address = server_socket.recvfrom(2048)
# Create response message
modified_message = message.upper()
server_socket.sendto(modified_message, client_address)
xxxxxxxxxx
'''
a library used to create end points.
heres a quick exemple of a client and a local TCP server:'''
#server file
import socket
soc = socket.socket(socket.AF_INET) #initializing the socket
IP = "111.111.1.111" #the ip of the server. use 'ipconfig' on cmd to check your ip address (make sure its ipv4 because its a local server)
PORT = 5050 #the port of the server. can be any port as long its not in use
soc.bind((IP,PORT)) #binding the ip and the port of the server
soc.listen() #letting the server accept clients
client, address = soc.accept() #waiting for a user to connect and store the user in the client variable and them address to the adress variable
client.send(b'hello client!') #sending a byte string to the client.
#client file (can be created from a different pc):
soc = socket.socket(socket.AF_INET) #initializing the socket
IP = "111.111.1.111" #the ip of the server.
PORT = 5050 #the port of the server.
soc.connect((IP,PORT)) #connecting to the server.
print(soc.recv(1024).decode()) #receiving the byte string from the server. passing as a parameter how much bytes we want to recieve. and we printing it on the string (the .decode() is used to decode the bytes)
xxxxxxxxxx
#1) Installation
#Go to your cmd and type pip install websockets
#2) Utilisation
#Here’s how a client sends and receives messages:
import asyncio
import websockets
async def hello():
async with websockets.connect("ws://localhost:8765") as websocket:
await websocket.send("Hello world!")
await websocket.recv()
asyncio.run(hello())
#And here’s an echo server:
import asyncio
import websockets
async def echo(websocket):
async for message in websocket:
await websocket.send(message)
async def main():
async with websockets.serve(echo, "localhost", 8765):
await asyncio.Future() # run forever
asyncio.run(main())
xxxxxxxxxx
import socket
addr = ("", 8080) # all interfaces, port 8080
if socket.has_dualstack_ipv6():
s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True)
else:
s = socket.create_server(addr)