套接字消息客户端/服务器:客户端未发送消息

时间:2019-08-25 22:45:02

标签: python sockets

我正在尝试使用Python和Socket创建一个简单的聊天程序。服务器处理两个客户端之间的连接。每当我运行该程序时,对于其中一个客户端,第一个之后的每条消息都不会发送。该消息甚至无法到达服务器。

这是在Windows,Python3上。我已经集成了线程,因此可以同时发送和接收消息。但是,问题仍然存在。

Server.py

? Generators to update (Press <space> to select, <a> to toggle all, <i> to invert selection)generator-jhipster
Unhandled rejection Error: EACCES: permission denied, open '/home/lelo/.npm/_cacache/index-v5/ad/54/831265f841b3fd278d23c4c96b06a32656a62c88fddaa7739f419602a04d'

npm ERR! cb() never called!

npm ERR! This is an error with npm itself. Please report this error at:
npm ERR!     <https://npm.community>

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/lelo/.npm/_logs/2019-08-25T22_22_40_369Z-debug.log```

Client.py

conns = [] # list that stores both connections


def accept(sk):
    while True:
        conn, addr = sk.accept()
        conns.append(conn)
        print(addr, "has connected")

    t = threading.Thread(target=accept, args=(sk,))
    t.start() #start accept thread



def send(conn):
    while True:
        message = conn.recv(2048)
        print(message)
        for conn in conns:
            conn.send(message) #sends message to every connection
            print("Sent message")


t = threading.Thread(target=send, args=(conn,))
t.start() #start threading for send

所有消息都应从两个客户端发送,但是一个客户端永远不能发送多条消息,另一个客户端可以正常工作。

1 个答案:

答案 0 :(得分:0)

在您的示例中,您的服务器代码丢失了套接字,并且没有运行接受,正如James指出的那样,您的缩进也无效,下一次提供minimal reproducible example

我还整理了一些文件,因为您遵循了一些错误的做法,特别是将消息广播到实际接收的所有客户端“ def send”,以避免混淆命名:)

在您的服务器代码中,您还仅发送到一个连接(在您的示例中不存在),该连接应在每次接收到新消息时都运行接收和发送

server.py

import socket
import threading

conns = []  # list that stores both connections


def accept(sk):
    while True:
        conn, addr = sk.accept()
        conns.append(conn)
        print(addr, "has connected")

        # receive from new client
        receive_t = threading.Thread(target=receive, args=(conn,))

        receive_t.start()  # start threading for send


def send(s, msg):

        # change message ..
        s.send(msg)  


def broadcast(msg):
    for conn in conns:
        send(conn, msg)


def receive(conn):
    try:
        while True:
            message = conn.recv(2048)

            if not message: # detects if socket is dead, by testing message
                print("client sent Nothing, removing") 
                conns.remove(conn)
                break
            broadcast(message)  # send to all clients
    except ConnectionResetError  as e:
        print('Could not send must be disconnected ')
        conns.remove(conn) # remove dead socket



# added missing socket
sock = socket.socket()
sock.bind(('127.0.0.1', 8080))
sock.listen(1)  # needs to  bind and listen
t = threading.Thread(target=accept, args=(sock,))
t.start()  # start accept thread

client.py

import os
import socket
import threading

messages = []


def recvMessages(s):
    while True:
        message = s.recv(2048)

        message = message.decode()
        print('new message= ', message)
        messages.append(message)
        os.system("cls")

        for message in messages:
            print(message)


def send_message(s):
    while True:
        message = input()
        message = message.encode()
        s.send(message)


s = socket.socket()
host = '127.0.0.1'
port = 8080
s.connect((host, port))

print("Connected")
connected = True
# added missing receive

receive = threading.Thread(target=recvMessages, args=(s,)) # missed receive thread in example
receive.start()
send_message(s)

我在回答问题上还不够完善,因此,如果需要更多说明,请告诉我。