【问题标题】:Networking issues, possible to resolve with async method?网络问题,可以用异步方法解决吗?
【发布时间】:2015-03-19 16:47:21
【问题描述】:

我正在学习使用网络库 Lidgren。我试图让一个基本的客户端/设置服务器运行,但我收到了一个错误。到目前为止,我只有服务器,当我运行它时,服务可能会运行 10 秒,然后崩溃,Lidgren.Network.NetException 除外。如果我删除第一个 while 循环,则不会发生这种情况,该循环旨在继续检查消息。有关异常的附加信息如下:Additional information: Trying to read past the buffer size - likely caused by mismatching Write/Reads, different size or order.

谁能帮我解决这个问题? 另外,我是否可以通过尝试异步读取消息来避免这种情况?如果是,我将如何做到这一点?

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lidgren.Network;

namespace ConsoleApplication3
{
    class Program
    {
        private static void Main(string[] args)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("MyExampleName");
            config.Port = 14242;

            NetServer server = new NetServer(config);
            server.Start();
            Console.WriteLine("Server Started...");

            bool listen = true;
            while (listen)
            {
                NetIncomingMessage msg;
                while ((msg = server.ReadMessage()) != null)
                {
                    Console.WriteLine("Started Listening...");
                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.DebugMessage:
                        case NetIncomingMessageType.WarningMessage:
                        case NetIncomingMessageType.Data:
                            if (msg.ReadString() == "bye")
                            {
                                listen = false;
                            }
                            else
                            {
                                Console.WriteLine(msg.ReadString());
                            }
                            break;
                        case NetIncomingMessageType.ErrorMessage:
                            Console.WriteLine(msg.ReadString());
                            break;
                        default:
                            Console.WriteLine("Unhandled type: " + msg.MessageType);
                            break;
                    }
                    server.Recycle(msg);
                }
            }
            Console.WriteLine("Finished Listening!");
            Console.ReadLine();
        }
    }
}

【问题讨论】:

    标签: c# networking asynchronous console-application lidgren


    【解决方案1】:

    该错误通常意味着您没有按照发送它们的顺序读取相同的数据类型。看起来上面的代码读取了一个字符串 - 你发送什么?此外,您应该在退出循环时调用 server.Shutdown()。

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2019-03-27
      • 2019-02-13
      • 1970-01-01
      相关资源
      最近更新 更多