TCP python sockets programming

July 17, 2020

  • server1.jpg Back-End

Simple client - server

from socket import *

HOST = ''   # all available interfaces
PORT = 1060

s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(5)

while(1):
    print "Waiting..."
    client, addr = s.accept()
    print 'Got connection from', addr
    data = client.recv(1024)
from socket import *
from time import *

HOST = '127.0.0.1'
PORT = 1060

remote = socket(AF_INET, SOCK_STREAM)
remote.connect((HOST,PORT))
remote.send("Hi there!")
data = remote.recv(1024)

Sending and receiving fixed length messages

from socket import *

HOST = ''   # all available interfaces
PORT = 1060

def recv_all(sock, length):
    data = ''
    while len(data) < length:
        chunk = sock.recv(length - len(data))
        if not chunk:
            raise RuntimeError('socket closed: read only %d bytes from a %d-byte message' % (len(data), length))
        data += chunk

    return data

s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(5)

while True:
    print "Waiting..."
    client, addr = s.accept()
    print 'Got connection from', addr
from socket import *
from time import *

HOST = '127.0.0.1'
PORT = 1060

def send_all(sock,msg):
    totalsent = 0
    while totalsent < len(msg):
        sent = sock.send(msg[totalsent:])
        if sent == 0:
            raise RuntimeError("socket connection broken")
        totalsent = totalsent + sent


remote = socket(AF_INET, SOCK_STREAM)
remote.connect((HOST,PORT))

msg = ('0' * 1024 * 1024).encode('utf-8')

#remote.sendall(msg)
#or
send_all(remote,msg)

data = remote.recv(1024)

Return to home