Home > Software design >  Why one method works but another similar method does not work?
Why one method works but another similar method does not work?

Time:03-10

I started to learn sockets and I saw a video on Youtube which explain it, I took some code and I didn't understand some line.

 import socket
import threading

HOST = 'localhost'
PORT = 9090
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
# Lists For Clients and Their Nicknames
clients = []
nicknames = []
#send message to all clients
def broadcast(message):
    for client in clients:
        client.send(message)
def handle(client):
    while True:
        try:
            # Broadcasting Messages
            message = client.recv(1024)
            broadcast(message)
        except:
            # Removing And Closing Clients
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            broadcast('{} left!'.format(nickname).encode('ascii'))
            nicknames.remove(nickname)
            break 
def receive():
    while True:
        # Accept Connection
        client, address = server.accept()
        print("Connected with {}".format(str(address)))
        # Request And Store Nickname
        client.send('NICK'.encode('ascii'))
        client.send('check it'.encode('ascii'))
        nickname = client.recv(1024).decode('ascii')
        nicknames.append(nickname)
        clients.append(client)
        # Print And Broadcast Nickname
        print("Nickname is {}".format(nickname))
        broadcast("{} joined!".format(nickname).encode('ascii'))
        client.send('Connected to server!'.encode('ascii'))
        # Start Handling Thread For Client
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()
receive()

Inside the while loop, I didn't understand why does the client get the text - "check it" client.send('check it'.encode('ascii')) but he didn't get the text - "NICK" - client.send('NICK'.encode('ascii'))

CodePudding user response:

Your client code should have use s.recv to check for NICK and send the client response back, e.g.:

s.send(input(s.recv(1024).decode('ascii')).encode('ascii'))
  1. It receives the NICK,
  2. prompts that via input to ask client for input and
  3. sends the user input back to server.

This worked fine for me. It could be an issue with the client code which OP did not include. It works well for the client code below.

import socket
import threading

# separate thread to ask user for input
def send_message(s):
    while True:
        msg = input('message: ')
        if msg == 'exit':
            s.close()
            break
        s.send(msg.encode('ascii'))


def connect():
    s = socket.socket()
    address = '127.0.0.1'
    port = 8080  # port number
    s.connect((address, port))

    # receives 'NICK', prompts user for input, sends input back to server
    s.send(input(s.recv(1024).decode('ascii')).encode('ascii'))

    # starts thread to prompt user for messages to broadcast to other users via server
    thread = threading.Thread(target=send_message, args=(s,))
    thread.start()

    # check for messages from the server and print them
    while True:
        try:
            print(s.recv(1024).decode('ascii'))
        except:
            break


if __name__ == '__main__':
    connect()
  • Related