gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:04:40 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com