So far I managed to get the server to communicate with multiple clients but I need to pass a value from one client to another.
Server code
import socket
from _thread import *
ServerSideSocket = socket.socket()
host = ''
port = 2004
ThreadCount = 0
try:
ServerSideSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Socket is listening..')
ServerSideSocket.listen(5)
def multi_threaded_client(connection):
connection.send(str.encode('Server is working:'))
while True:
data = connection.recv(2048)
response = data.decode('utf-8')
if not data:
break
connection.sendall(str.encode(response))
connection.close()
while True:
Client, address = ServerSideSocket.accept()
print('Connected to: ' address[0] ':' str(address[1]))
start_new_thread(multi_threaded_client, (Client,))
ThreadCount = 1
print('Thread Number: ' str(ThreadCount))
ServerSideSocket.close()
Client code
import socket
ClientMultiSocket = socket.socket()
host = '127.0.0.1'
port = 2004
print('Waiting for connection response')
try:
ClientMultiSocket.connect((host, port))
except socket.error as e:
print(str(e))
res = ClientMultiSocket.recv(1024)
while True:
Input = input('Hey there: ')
ClientMultiSocket.send(str.encode(Input))
res = ClientMultiSocket.recv(1024)
print(res.decode('utf-8'))
ClientMultiSocket.close()
I need the value from client1 to be passed to client2 and so forth, is there any way I can do that in python?
CodePudding user response:
A TCP connection can only established to a socket which is a) bound to the specific address one is trying to connect to and b) is listening on this address for new connections which it then will c) accept to create a new socket which will then be used to communicate on this connection. Any communication outside such established connection is not possible in TCP.
The combination of a, b and c basically describes what a TCP server does. This also means that it is not possible to communicate between two TCP clients only which only called connect
to each other. In order for a connect
to succeed there must be something bound to the socket, listening to it and accepting connections on it (i.e. a, b and c - a TCP server).
A common way to implement the use cases of passing messages between different client (like in a chat server) is to send the message and intended client id to the server and let the server forward it to the intended client.
CodePudding user response:
In a TCP connection, always, one is the server and the other are the client.
A simple use case:
client1 need to send a msg to client2, the pipeline could be:
- client1 send a msg in JSON format to server "{'msg': 'abc', 'receiver':'client2'}"
- server will store this info in a dict (or another structure you want)
- client2 will ask for the server if there is any message to it
- the server send the message stored to client2
It's more or less in this way that all the communications apps works.