Blog

Home  /  Coding   /  How To Use Socket in Python | AV Coding

How To Use Socket in Python | AV Coding

Hey guys welcome to AV Coding

Today we will learn how to use socket in python and build an simple communicating app in python.

The complete code is explained in the video below and the source code is provided below.

from threading import Thread
import socket
socket.SO_REUSEPORT = socket.SO_REUSEADDR

sock, peers = None, []

class IMS(object):
    MAX_CONNECTIONS = 5

    def __init__(self):
        self.setup()
        for i in range(IMS.MAX_CONNECTIONS):
            thread = IMS.Connection()
            thread.daemon = True
            thread.start()

    def setup(self):
        global sock
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        sock.bind(('localhost', 9999,))
        sock.listen(10)

    def send_message(self, message):
        for peer in peers:
            peer.sendall(message)

    class Connection(Thread):
        def __init__(self):
            Thread.__init__(self)
        def run(self):
            peer, addr = sock.accept()
            peers.append(peer)
            while True:
                message = peer.recv(1024)
                print(message.decode('utf-8'))
                for other in peers:
                    if peer != other:
                        other.sendall(message.encode('utf-8'))

ims = IMS()
try:
    while 1:
        message = input('')
        ims.send_message(message.encode('utf-8'))
except KeyboardInterrupt:
    sock.close()
    for peer in peers:
        peer.close()
from threading import Thread
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 9999,))


class ReplyHandler(Thread):
    def __init__(self):
        Thread.__init__(self)
    def run(self):
        while True:
            reply = sock.recv(1024)
            print(reply.decode('utf-8'))

thread = ReplyHandler()
thread.daemon = True
thread.start()

while True:
    message = input('')
    sock.sendall(message.encode('utf-8'))

Hope You Liked This Blog. Share, Comment, Subscribe And Press The Bell Icon In The Bottom Right Side For More Code Feeds.