从套接字服务器接收新数据时更新终端

时间:2019-04-20 14:50:21

标签: python sockets ncurses

我正在尝试使用终端和curses在python上创建网络聊天客户端。但是,当recv上有新数据时,我无法使其刷新,我需要发送一条消息,然后它才能获取数据...

这是代码:

chat_msg_list = list()
global_chat = curses.newwin(10, 50, 2, 23)
user_chat = curses.newwin(3, 45, 22, 32)

ready = select.select([s], [], [], 0)
if ready[0]:
      data = s.recv(1024)
      chat_msg_list.append(data.decode())
      for i in range(len(chat_msg_list)):
          global_chat.addstr(i, 1, chat_msg_list[ i ])
      global_chat.refresh()

但是,如果直到我按下CTRL + G才会发生:

    box = Textbox(user_chat)
    box.edit()
    message = box.gather()
    screen.nodelay(1)
    s.send(message.encode())

有什么想法,当recv上有新数据时,如何重绘屏幕?

编辑:根据要求提供完整示例:

def main(screen):
    """Main client order call and loop"""

    user_chat = curses.newwin(3, 45, 22, 32)
    user_chat.scrollok(True)
    user_chat.idlok(True)

    screen.addstr(0, 3, "Users List:")

    # Rectangles:

    rectangle(screen, 1, 0, 23,20)      # user list rectangle
    rectangle(screen, 1, 21, 19, 78)    # chat rectangle
    rectangle(screen, 21, 21, 23, 78)   # user input rectangle

    # Get the user name on screen
    user_name = login()
    screen.addstr(22, 22, user_name)
    # Help:
    screen.addstr(20, 25, "Press CTRL + G to send [CTRL + C exits]")
    screen.refresh()

    # Add the user list:
    user_list_box = curses.newwin(15, 19, 2, 1)
    data = s.recv(1024)
    chat_msg_list.append(data.decode())

    for i in range(len(user_list)):
        user_list_box.addstr(i, 1, user_list [ i ])

    # Global chat window:
    global_chat = curses.newwin(10, 50, 2, 23)

    for i in range(len(chat_msg_list)):
        global_chat.addstr(i, 1, chat_msg_list[ i ])
    global_chat.refresh()

    # Input from user:

    box = Textbox(user_chat)
    box.edit()
    message = box.gather()
    send_message = message_string(message, login())  # login should not come here.
    s.send(send_message)        # send msg to srv

if __name__ == '__main__':
        s.connect((HOST, PORT))

        try:
            screen = curses.initscr()
            while True:
                curses.wrapper(main)
        except KeyboardInterrupt:
            s.close()           # I believe the srv crash is here?
            sys.exit("Program Finished")

0 个答案:

没有答案