python 2.7 socket code example

Example 1: 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 2: python3 socket server

import socket
import os

sock_file = "/tmp/python_socket"

if os.path.exists(sock_file):
    os.remove(sock_file)

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(sock_file)
sock.listen()
print("Listening...")
while True:
    conn, _addr = sock.accept()
    datagram = conn.recv(1024)
    request = datagram.decode('utf-8')
    conn.send(str("Back at you:"+request).encode('utf-8'))