J.Fitz
J.Fitz

Reputation: 107

network communication using python and socket

I have succesfully made a code which starts a server which can be connected by other devices on my LAN with the CMD command telnet hostname port when the new "client" enters a word and presses enter the word is then sent back to them through the server. My question is if i connected 2 devices to the server how would i get the message to get sent from one to the server then back to the other. Like a messaging programme. The code i have used is shown below

import socket
import sys
from _thread import *

host = ''
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((host, port))
except socket.error as e:
    print(str(e))

s.listen(5)
print('Waiting for a connection.')

def threaded_client(conn):
    conn.send(str.encode('Welcome, type your info\n'))
    final_char = ""

    while True:
        data = conn.recv(2048)
        char = data.decode("utf-8")
        print(data)
        if data != b'\r\n':
            final_char += char
            print(final_char)
        else:


            reply = 'Server output: '+ final_char+"\n"
            if not data:
                break
            conn.sendall(str.encode(reply))
            final_char = ""
    conn.close()



while True:

    conn, addr = s.accept()
    print(addr)
    print(conn)
    print('connected to: '+addr[0]+':'+str(addr[1]))

    start_new_thread(threaded_client,(conn,))

Upvotes: 0

Views: 110

Answers (2)

epinal
epinal

Reputation: 1465

Take a look at ZQM the python library works perfect and it has already implemented what you need using sockets internally. https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/

Take a look at their publisher / subscriber message pattern.

Upvotes: 1

Matt Clark
Matt Clark

Reputation: 28639

Not an actual implementation, but some theory:

You need to keep a list of all the clients you have an active connection to:

while ( true )

    client = server.accept()

    clientList.add(client)

    startThread(client)

Then in the thread

while ( true )

    data = connection.receive()

    for client in clientList

        client.sendall( data )

Upvotes: 1

Related Questions