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,))
2 Answers 2
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 )
7 Comments
client to different threads in your pseudo-code.<socket.socket fd=728, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('host', port), raddr=('client ip', client port)>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.