0

I want to create a TCP server which can send specific messages to specific clients. In my example, I have two clients Iconet and Robot. I want to send specific messages to each of these clients once they are connected. I wish to send VITAi and VITAr to the clients respectively. Once i receive the response from the two clients i wish to jump to def chat() The aim is to get the response from clients and then jump to def chat() which acts like a chat room and displays the messages the clients have sent. How can i achieve this?

server


import threading 
import socket 

PORT = 1026
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER,PORT)
FORMAT = "utf-8"
HEADER = 1024
DISCONNECT_MESSAGE = "END_CYCLE"
VITA_R = "yes"
VITA_I = "yes"
robot_flag = False
iconet_flag = False

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
clients = []
aliases = []
alias_dictionary_iter = zip(aliases,clients)
alias_dictionary = dict(alias_dictionary_iter)

def broadcast(broadcast_message):
    for client in clients:
        client.send(broadcast_message)

def handle_client(client,addr):
    print(f"[NEW CONNECTION] {addr} connected.")
    connected = True
    while connected:
        for client in clients:
         if client == clients[0]:
            robot_message = 'VITAr'
            client.send(robot_message.encode(FORMAT))
            robot_response = client.recv(2048).decode(FORMAT)
            print(robot_response)
            if robot_response == VITA_R:
                robot_flag == True
            else:
                robot_flag == False
          
         elif client == clients[1]:
            iconet_message = 'VITAi'
            client.send(iconet_message.encode(FORMAT))
            iconet_response = client.recv(2048).decode(FORMAT)
            print(iconet_response)
            if iconet_response == VITA_I:
                iconet_flag == True
            else:
                iconet_flag == False
                    
def chat(client):
            while robot_flag & iconet_flag == True:
                try:
                    message = client.recv(1024)
                    broadcast(message)
                    print(message)
                except:
                    index = clients.index(client)
                    clients.remove(client)
                    client.close()
                    alias = aliases[index]
                    broadcast(f'{alias} has left the chat room!'.encode('utf-8'))
                    aliases.remove(alias)
                    break 
        

def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        client, addr = server.accept()
        print(f"[NEW CONNECTION] {addr} connected.")
        client.send('NAME?'.encode(FORMAT))
        alias = client.recv(1024)
        aliases.append(alias)
        clients.append(client)
        print(f'The clients is {alias}'.encode(FORMAT))
        thread = threading.Thread(target= handle_client, args=(client, addr))
        thread.start()


print ('[STARTING] server is starting')
start()

client

import threading
import socket
name = input('NAME? ')
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('0.0.0.0', 1026))


def client_receive():
    while True:
        try:
            message = client.recv(1024).decode('utf-8')
            if message == "NAME?":
                client.send(name.encode('utf-8'))
            else:
                print(message)
        except:
            print('Error!')
            client.close()
            break


def client_send():
    while True:
        message = f'{name}: {input("")}'
        client.send(message.encode('utf-8'))


receive_thread = threading.Thread(target=client_receive)
receive_thread.start()

send_thread = threading.Thread(target=client_send)
send_thread.start()
Sho
  • 21
  • 5
  • You can write the code to make the computer do the thing you want it to do. Right now you have a bunch of code that is making the computer do things you don't want it to do (like sending VITAr/VITAi over and over forever) and maybe you would find it easier to think about if you removed that stuff. – user253751 Jun 15 '22 at 11:37
  • I have tested the function blocks individually and they do work well, the problem arises when I try to combine them both – Sho Jun 15 '22 at 12:35
  • https://stackoverflow.com/a/43420503/238704 – President James K. Polk Jun 15 '22 at 13:30
  • maybe the code works by coincidence but it's all over the place. Tell me why is every client thread trying to talk to every client? So thread 0 talks to client 0, thread 0 talks to client 1, thread 1 talks to client 0, thread 1 talks to client 1? That's a mess. – user253751 Jun 15 '22 at 13:39
  • The aim was to send vita to each client desperately and then receive a response from them. So once both the clients have responded, the sim was to create a blackboard situation where the client can send a message which can be read by everyone who is connected – Sho Jun 15 '22 at 15:05

0 Answers0