"""
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)
from socket import *
# Set server name and port number
server_name = "localhost"
server_port = 12000
# Create a UDP socket using IPv4
client_socket = socket(AF_INET, SOCK_DGRAM)
# Get message to send to server
message = input("Input sentence to send to server:")
# Convert it into bytes
message_bytes = bytes(message, encoding='utf-8')
client_socket.sendto(message_bytes, (server_name, server_port))
# Wait for server's response
modified_message, server_address = client_socket.recvfrom(2048)
# Display it on screen
print(modified_message.decode("utf-8"))
client_socket.close()
#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())
import socket
import struct
import sys
# CAN frame packing/unpacking (see `struct can_frame` in <linux/can.h>)
can_frame_fmt = "=IB3x8s"
def build_can_frame(can_id, data):
can_dlc = len(data)
data = data.ljust(8, b'x00')
return struct.pack(can_frame_fmt, can_id, can_dlc, data)
def dissect_can_frame(frame):
can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
return (can_id, can_dlc, data[:can_dlc])
if len(sys.argv) != 2:
print('Provide CAN device name (can0, slcan0 etc.)')
sys.exit(0)
# create a raw socket and bind it to the given CAN interface
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
s.bind((sys.argv[1],))
while True:
cf, addr = s.recvfrom(16)
print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))
try:
s.send(cf)
except socket.error:
print('Error sending CAN frame')
try:
s.send(build_can_frame(0x01, b'x01x02x03'))
except socket.error:
print('Error sending CAN frame')