【问题标题】:i want that client can send private message also from a broadcast server socket python我希望客户端也可以从广播服务器套接字 python 发送私人消息
【发布时间】:2023-01-04 02:07:50
【问题描述】:

我已经制作了一个广播服务器和客户端,我使用了一条消息作为命令,如@private 作为命令工作,它将列出所有用户,然后我希望它应该选择其中一个,然后它只能与聊天只有他选择并在后端广播的那些客户也为其他人工作

服务器()

# import socket programming library
import socket
import time
# import thread module
from _thread import *
import threading

def chatwithtwo(c,username,numusr,data):
            c.send("choose to which one you wanna chat".encode())
            for i in range(len(username)):
                select=f"{i}. {username[i]}\n"
                c.send(select.encode())
            #here the thread gives problem
            select_username=c.recv(1024)
            print("select:",select_username.decode())
            try:
                if username[int(select_username)] in username:
                        chat_two_display(numusr,c,clients[int(select_username)])
                else:
                    c.send("wrong selection".encode())
            except:
                c.send("wrong input".encode())
            lock.release()
def chat_two_display(numusr,c,recver):
    sendcheck={}
    while True:
        data = c.recv(1024)
        sendcheck[numusr]=c
        for i in range(len(clients)):
            if clients[i]==recver:
                send_to=usernames[i]
        print(f"[+] {numusr} --> {send_to}:- {data.decode()}")
        chat_two_send(numusr,data.decode(),recver)
def chat_two_send(numusr,data,recver):
    sendingtoall=f"[+] {numusr} (private):- {data}"
    recver.send(sendingtoall.encode())

def send_data(numusr,senddata,clients,sendcheck):
    lock.release()
    for i in range(len(clients)):
        if not clients[i]==sendcheck[numusr]:
            sendingtoall=f"[+] {numusr}:- {senddata}"
            clients[i].sendall(sendingtoall.encode())
def display_data(c,numusr):
        global lock
        lock=threading.Lock()
        sendcheck={}
        while True:
            time.sleep(0.5)
            data = c.recv(1024)
            sendcheck[numusr]=c
            print(f"[+] {numusr}:- {data.decode()}")
            lock.acquire()
            if data.decode()=="@private":
                #thread.acquire()
                chatwithtwo(c,usernames,numusr,data)
                
            else:
                send_data(numusr,data.decode(),clients,sendcheck)
# thread function
def threaded(clients,username):
    for i in range(len(clients)):
        threading.Thread(target=display_data,args=(clients[i],username[i])).start()
def username_check(c):
    while True:
                uname=c.recv(1024)
                if uname.decode() not in usernames:
                    datatosend=f"your username is {uname.decode()}"
                    usernames.append(uname.decode())
                    clients.append(c)
                    c.sendall(datatosend.encode())
                    break
                else:
                    c.send("[-] This username is alredy in use!!!".encode())


def Main():
    host = "127.0.0.1"

    # reserve a port on your computer
    # in our case it is 12345 but it
    # can be anything
    port = 8000
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    print("socket binded to port", port)

    # put the socket into listening mode
    s.listen(5)
    print("socket is listening")
    global clients
    global usernames
    global threads
    clients=[]
    usernames=[]
    threads=[]
    connectio(s)

def connectio(s):
    while True:

        # establish connection with client
        c, addr = s.accept()

        # lock acquired by client
        print('Connected to :', addr[0], ':', addr[1])
        username_check(c)
        # Start a new thread and return its identifier
        threaded(clients,usernames)


if __name__ == '__main__':
    Main()

客户()

import socket
import threading
import time

def send_data(s):
    while True:
        message=input("")
        s.send(message.encode('ascii'))
        time.sleep(0.5)
        if message=="close":
            s.close()

def display_data(s):
    while True:
        data = s.recv(1024)
        print(str(data.decode('ascii')))
        time.sleep(0.5)
    
def Main():
    # local host IP '127.0.0.1'
    host = '127.0.0.1'
 
    # Define the port on which you want to connect
    port = 8000
 
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 
    # connect to server on local computer
    s.connect((host,port))
    while True:
        username=input("enter your username which should be unique:-")
        s.send(username.encode())
        username_check=s.recv(1024)
        print(username_check.decode())
        if username_check:
            if username_check.decode()!="Try again":
                break

    # message you send to server
    threading.Thread(target=send_data,args=(s,)).start()
    threading.Thread(target=display_data,args=(s,)).start()
    # close the connection
 
if __name__ == '__main__':
    Main()



我已经为它调用了一个函数chatwithtwo()但问题是什么时候选择用户名变量正在接收值其他线程也在同时工作所有搞砸了请帮我解决这个问题

【问题讨论】:

标签: python sockets server chat broadcast


【解决方案1】:

只需从线程函数中删除你的 for i in range(len(clients)): 就可以了

每次客户端连接到服务器时,它都会运行您的线程,就像如果一个客户端已连接,那么它将运行 1 次 threads=1 running 然后第二次运行然后它的值将为 2 并且循环将运行两次并且线程值填充被添加到最后一个,就像现在运行的线程是 1,在循环 2 之后将添加更多线程,现在线程是 3 等等。

【讨论】:

    猜你喜欢
    • 2013-04-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多