Answers for "socket listen python"

3

python socket select

import select
import socket
import sys
import Queue

# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)

# Bind the socket to the port
server_addr = ('localhost', 10000)
print('starting server on {server_addr[0]}:{server_addr[1]}')
server.bind(server_address)
server.listen(5)

# Sockets from which we expect to read
inputs = [ server ]

# Sockets to which we expect to write
outputs = [ ]

# Outgoing message queues (socket:Queue)
message_queues = {}

while inputs:

    # Wait for at least one of the sockets to be ready for processing
    print('waiting for the next event')
    readable, writable, exceptional = select.select(inputs, outputs, inputs)

    # Handle inputs
    for s in readable:
        if s is server:
            # A "readable" server socket is ready to accept a connection
            connection, client_address = s.accept()
            print(f'new connection from {client_address}')
            connection.setblocking(False)
            inputs.append(connection)

            # Give the connection a queue for data we want to send
            message_queues[connection] = Queue.Queue()
        else:
            data = s.recv(1024)
            if data:
                # A readable client socket has data
                print(f'received "{data}" from {s.getpeername()}')
                message_queues[s].put(data)
                # Add output channel for response
                if s not in outputs:
                    outputs.append(s)
            else:
                # Interpret empty result as closed connection
                print(f'closing {client_address} after reading no data')
                # Stop listening for input on the connection
                if s in outputs:
                    outputs.remove(s)
                inputs.remove(s)
                s.close()
                
                # Remove message queue
                del message_queues[s]

    # Handle outputs
    for s in writable:
        try:
            next_msg = message_queues[s].get_nowait()
        except Queue.Empty:
            # No messages waiting so stop checking for writability.
            print(f'output queue for {s.getpeername()} is empty')
            outputs.remove(s)
        else:
            print(f'sending "{next_msg}" to {s.getpeername()}')
            s.send(next_msg)

    # Handle "exceptional conditions"
    for s in exceptional:
        print(f'handling exceptional condition for {s.getpeername()}')
        # Stop listening for input on the connection
        inputs.remove(s)
        if s in outputs:
            outputs.remove(s)
        s.close()
        # Remove message queue
        del message_queues[s]
Posted by: Guest on June-16-2021
1

socket python functions

#!/usr/bin/env python3

import socket

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 65432        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))
Posted by: Guest on June-09-2021
5

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)
Posted by: Guest on November-27-2020
0

socket python functions

conn, addr = s.accept()
with conn:
    print('Connected by', addr)
    while True:
        data = conn.recv(1024)
        if not data:
            break
        conn.sendall(data)
Posted by: Guest on June-09-2021
0

socket python functions

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    pass  # Use the socket object without calling s.close().
Posted by: Guest on June-09-2021
0

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'x01x02x03'))
               except socket.error:
                       print('Error sending CAN frame')
Posted by: Guest on February-24-2021

Python Answers by Framework

Browse Popular Code Answers by Language