multithreading - 基于网络的消息传递程序的同时输入和输出

标签 multithreading sockets python-3.x

在 python 中,我正在创建一个消息系统,其中客户端和服务器可以同时来回发送消息。这是我的客户代码:

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")


class Recieve(threading.Thread):
    def run(self):
        while True: # Recieve loop
            r_msg = s.recv(buff).decode()
            print("\nServer: " + r_msg)

recieve_thread = Recieve()
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() )

s.close()

我在后台有一个线程来检查服务器消息和一个循环输入以将消息发送到服务器。当服务器发送消息并且用户输入立即反弹以为服务器消息腾出空间时,就会出现问题。我希望它使输入保持固定在 shell 窗口的底部,而输出从第二行打印出来,只留下第一行。有人告诉我你可以使用 curses 或 Queues 来做到这一点,但我不确定哪一个最适合我的情况,也不知道如何在我的项目中实现这些模块。

任何帮助,将不胜感激。谢谢你。

最佳答案

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



这是使用 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()

它更改滚动区域以省略屏幕的底线,临时进入滚动区域以输出服务器消息,并在最后将其更改回来。

关于multithreading - 基于网络的消息传递程序的同时输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32855095/

相关文章:

c++ - timespec 初始化时非阻塞 TCP 套接字挂起 (C++)

java - 我无法将套接字从 android 客户端连接到 java 服务器

python - 从大字典中弹出 N 项的最快方法

android - 第二次运行线程使应用程序崩溃

sockets - 创建RAW套接字教程/说明?

java - 终止线程的更复杂的方法(守护线程或 Thread.interrupt())

python - 使用Python分离列表数据

python - 如何删除 itertools.product 函数的镜像反射值?

java - 为什么我的生产者消费者死锁(或活锁)?

c# - 多线程 COMObject 和 UI 线程 (C#)