服务器为什么不从客户端接收消息?

时间:2019-08-15 20:54:43

标签: python sockets networking

我正在尝试使用具有某些外部功能的传统聊天服务器,但由于某些原因该服务器无法接收数据:

import socket
import select
import sys
import _thread


server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
IP_address = "127.0.0.1"
Port = 5454


server.bind((IP_address, Port))


server.listen(100)

list_of_clients = []


def clientthread(conn, addr):
    # sends a message to the client whose user object is conn
    conn.send(bytes("Welcome to this chatroom!", "utf8"))

    while True:
        try:
            message = conn.recv(2048)
            print(message)
            if message:
                print("<" + addr[0] + "> " + message)

                # Calls broadcast function to send message to all
                message_to_send = "<" + addr[0] + "> " + message
                broadcast(message_to_send, conn)

            else:
                print("removed")
                remove(conn)

        except:
            continue


def broadcast(message, connection):
    for clients in list_of_clients:
        if clients != connection:
            try:
                clients.send(bytes(message, "utf8"))
            except:
                clients.close()

                # if the link is broken, we remove the client
                remove(clients)





def remove(connection):
    if connection in list_of_clients:
        list_of_clients.remove(connection)


while True:

    conn, addr = server.accept()


    list_of_clients.append(conn)

    # prints the address of the user that just connected
    print(addr[0] + " connected")

    # creates and individual thread for every user
    # that connects
    _thread.start_new_thread(clientthread, (conn, addr))

conn.close()
server.close()

和客户:

import socket
import select
import sys
from file_utils import client_message_observer as ob



def callback():
    print("message.txt was modified")
    return True

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

IP_address = "127.0.0.1"
Port = 5454
server.connect((IP_address, Port))
observer = ob.FileModifiedHandler("client_data/", "message.txt", callback())
server.send(bytes("aloooo"))
while True:

    # maintains a list of possible input streams
    sockets_list = [sys.stdin, server]
    read_sockets, write_socket, error_socket = select.select(sockets_list, [], [])

    for socks in read_sockets:
        if socks == server:
            message = socks.recv(2048)
            print(message)
            #write to file
        else:
            if (observer.callback == True):
                message = open("client_data/message.txt").readline()
                server.send(bytes(message, "utf8"))
                print("send")
server.close()

没有一张测试照片出现。

代码不是很清楚,它侦听message.txt文件中的更改,并且在修改文件后,应将文本作为消息发送到服务器。我没有添加观察者的代码,但是我对其进行了测试,并且它可以工作。但是我不知道服务器为什么不响应客户端?

0 个答案:

没有答案