python socket programming how to code example

Example 1: socket programming in python

#!/usr/bin/env python3

import socket

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

Example 2: socket programming in python

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

Example 3: python can socket

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'\x01\x02\x03'))
               except socket.error:
                       print('Error sending CAN frame')