简体   繁体   中英

How to communicate with clients from python socket server individually?

I'd like to be able to communicate individually with clients. When client will connect to server, it will send its name. On server I will type clients name and message and the message will go ONLY to the client with that name. This is what I have but it doesn't work:

SERVER:

import socket
s = socket.socket()
ip = "localhost"
port = 7000
s.bind((ip, port))
s.listen(5)
while True:
    c, addr = s.accept()
    name = c.recv(1024).decode()
    ask = input("Enter client's name: ")
    msg = input("Enter message: ")
    if name == ask:
        c.send(bytes(msg, 'utf-8'))
    else:
        print("No client with this name")

CLIENTS:

import socket
c = socket.socket()
ip = "localhost"
port = 7000
c.connect((ip, port))
name = "C1"
c.send(bytes(name, 'utf-8'))
while True:
    msg = c.recv(1024).decode()
    print(msg)
import socket
c = socket.socket()
ip = "localhost"
port = 7000
c.connect((ip, port))
name = "C2"
c.send(bytes(name, 'utf-8'))
while True:
    msg = c.recv(1024).decode()
    print(msg)

I will appreciate your advices:)

The following code is for your reference.

You need to be careful how to close the connection.

import socket
import threading


s = socket.socket()
ip = "localhost"
port = 7000
s.bind((ip, port))
s.listen(5)

_map = {}


def get_recv(sock):
    name = sock.recv(1024).decode()
    _map.update({name: sock})


def send_msg():
    while True:
        ask = input("Enter client's name: ")
        msg = input("Enter message: ")
        sock = _map.get(ask)
        try:
            if sock:
                sock.send(bytes(msg, 'utf-8'))
            else:
                print("No client with this name")
        except BrokenPipeError:
            print("Client connection is broken.")
            sock.close()
            _map.pop(ask)


threading.Thread(target=send_msg, daemon=True).start()
while True:
    sock, addr = s.accept()
    threading.Thread(target=get_recv, args=(sock, ), daemon=True).start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM