Simultaneous input and output for network based messaging program

后端 未结 1 554
时光说笑
时光说笑 2021-01-25 16:32

In python, I am creating a message system where a client and server can send messages back and forth simeltaneously. Here is my code for the client:

import threa         


        
相关标签:
1条回答
  • 2021-01-25 17:24

    I want it so that the input stays pinned to the bottom of the shell window, while the output is printed from the 2nd line up, leaving the first line alone. I have been told that you can use curses

    Here's a supplemented version of your client code using curses.

    import threading
    import socket
    
    # Global variables
    host = input("Server: ")
    port = 9000
    buff = 1024
    
    # Create socket instance
    s = socket.socket()
    
    # Connect to server
    s.connect( (host, port) )
    print("Connected to server\n")
    
    import sys
    write = sys.stdout.buffer.raw.write
    from curses import *
    setupterm()
    lines = tigetnum('lines')
    change_scroll_region = tigetstr('csr')
    cursor_up            = tigetstr('cuu1')
    restore_cursor       = tigetstr('rc')
    save_cursor          = tigetstr('sc')
    
    def pin(input_lines):   # protect input_lines at the bottom from scrolling
            write(save_cursor + \
                  tparm(change_scroll_region, 0, lines-1-input_lines) + \
                  restore_cursor)
    
    pin(1)
    
    class Recieve(threading.Thread):
        def run(self):
            while True: # Recieve loop
                r_msg = s.recv(buff).decode()
                write(save_cursor+cursor_up)
                print("\nServer: " + r_msg)
                write(restore_cursor)
    
    recieve_thread = Recieve()
    recieve_thread.daemon = True
    recieve_thread.start()
    
    while True: # Send loop
        s_msg = input("Send message: ")
    
        if s_msg.lower() == 'q': # Quit option
            break
    
        s.send( s_msg.encode() )
    
    pin(0)
    s.close()
    

    It changes the scrolling region to leave out the screen's bottom line, enters the scrolling region temporarily to output the server messages, and changes it back at the end.

    0 讨论(0)
提交回复
热议问题