create socket python 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: tcp client using sockets in python

from socket import *
import sys
import json


serverName = ""
serverPort = 6100


clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))

sample_data = {
	"Aparna" : 1,
	"Pooja" : 2,
	"Shreya" : 3,
	"Tanishq" : 4
}

serialized_data = json.dumps(sample_data) #data serialized

# clientSocket.send(str.encode(sample_data))
clientSocket.send(str.encode(serialized_data))

response_data = clientSocket.recv(1024)
print("Response data from server : ", response_data.decode())

clientSocket.close()

Example 3: python socket

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 4: tcp server using sockets in python

import socket
from socket import *
import json

serverPort = 6100
serverSocket = socket(AF_INET, SOCK_STREAM)
# Avoiding : Python [Errno 98] Address already in use


serverSocket.bind(("", serverPort))
serverSocket.listen(1)

# TCP Server
print("The server is listening on PORT 6100")

while 1:

	connectionSocket, addr = serverSocket.accept()
	data = connectionSocket.recv(1024)

	# De-serializing data
	data_loaded = json.loads(data)
	
	print("client Sent :\n ", data_loaded)
	
	# Sending response
	connectionSocket.send(str.encode("Mil gya data"))


connectionSocket.close()

Example 5: 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')

Example 6: client server python socket

s = socket.socket (socket_family, socket_type, protocol=0)

Tags:

Misc Example