在收到消息(套接字)后移动Console.WriteLine()

本文关键字:Console WriteLine 移动 套接字 消息 | 更新日期: 2023-09-27 18:27:54

我已经使用套接字创建了一个控制台聊天应用程序。在服务器和客户端上,我都使用Console.WriteLine("Enter message:")。现在,当我在控制台中收到来自客户端或服务器的消息时,它会显示:

"Enter message:
 Received message"

如何将Console.WriteLine("Enter Message");自动移动到所有接收到的消息下面?

我当前的服务器代码:

 static void Main(string[] args)
    {
        var ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        Console.WriteLine("Enter a username:");
        var sname = Console.ReadLine();
        Console.Clear();
        ClientSocket.Connect(new IPEndPoint(IPAddress.Loopback, 9000));
        Console.WriteLine("Connection has been established...");
        var RecieveThread = new Thread(new ParameterizedThreadStart(RecieveMessage));
        RecieveThread.Start(ClientSocket);
        while (true)
        {
            Console.Clear();
            Console.WriteLine("Type message:");
            var message = Console.ReadLine();
            var custmessage = new CustomMessage() { From = sname, Message = message, TimeStamp = DateTime.Now };
            Serialize serialize = new Serialize();
            ClientSocket.Send(serialize.Serializer(custmessage));
        }
    }
    static void RecieveMessage(object socketobject)
    {
        Serialize deserialize = new Serialize();
        var client = (Socket)socketobject;
        while (true)
        {
            byte[] buffer = new byte[1024];
            var newmessage = new CustomMessage();
            client.Receive(buffer);
            object desbuffer = deserialize.Deserializer(buffer);
            newmessage = (CustomMessage)desbuffer;
            Console.WriteLine(newmessage.ToString());
        }
    }`

在收到消息(套接字)后移动Console.WriteLine()

您可以使用Console.CursorTop移动到屏幕上的最后一行,输出"输入消息",然后返回。

下面是一个示例,展示了如何在控制台中的任意点输出文本。