线程安全服务器

本文关键字:服务器 安全服 安全 线程 | 更新日期: 2023-09-27 18:30:39

我尝试实现多线程服务器。很少有客户端(<10)会向服务器发送一些数据(PUT请求)。在GET服务器上,服务器必须发送包含此数据的集合。这是我的服务器代码:

class Server
{
    private HttpListener httpListener;
    private static System.Threading.AutoResetEvent listenForNextRequest = new System.Threading.AutoResetEvent(false);
    public static BlockingCollection<NodeInfo> locations = new BlockingCollection<NodeInfo>();
    public Server()
    {
        const string ip = "127.0.0.1";
        const int port = 9999;
        string prefix = String.Format("http://{0}:{1}/", ip, port.ToString());
        httpListener = new HttpListener();
        httpListener.Prefixes.Clear();
        httpListener.Prefixes.Add(prefix);
        Console.WriteLine("HTTP server is running ...");
        Console.WriteLine("Listening on {0} ...'n", prefix);
    }
    public void Start()
    {
        httpListener.Start();
        ThreadPool.SetMaxThreads(10, 10);
        ThreadPool.QueueUserWorkItem(new WaitCallback(Listen));
        Thread.Sleep(7000);
    }
    internal void Stop()
    {
        httpListener.Stop();
    }
    private void Listen(object state)
    {
        while (httpListener.IsListening)
        {
            httpListener.BeginGetContext(new AsyncCallback(ListenerCallback), httpListener);
            listenForNextRequest.WaitOne();
        }
    }
    private static void ListenerCallback(IAsyncResult result)
    {
        HttpListener listener = (HttpListener)result.AsyncState;
        // Request
        HttpListenerContext context = listener.EndGetContext(result);
        if (context.Request.HttpMethod.Equals("PUT"))
        {
            PutRequestProcess(context);
        }
        if (context.Request.HttpMethod.Equals("GET"))
        {
            GetRequestProcess(context);
        }
        // Process next request
        result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
    }
    private static void PutRequestProcess(HttpListenerContext context)
    {
        // Request object
        HttpListenerRequest request = context.Request;
        using (Stream stream = request.InputStream)
        {
            // Deserialize
            DataContractSerializer ser = new DataContractSerializer(typeof(NodeInfo));
            XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
            // Deserialize the data and read it from the instance.
            NodeInfo nodeInfo = (NodeInfo)ser.ReadObject(reader, true);
            reader.Close();
            stream.Close();
            locations.Add(nodeInfo);
        }
        // Response object
        HttpListenerResponse response = context.Response;
        response.StatusCode = (int)HttpStatusCode.OK;
        using (Stream stream = response.OutputStream)
        {
            stream.Close();
        }
    }
    private static void GetRequestProcess(HttpListenerContext context)
    {
        // Response object
        HttpListenerResponse response = context.Response;
        response.StatusCode = (int)HttpStatusCode.OK;
        using (Stream stream = response.OutputStream)
        using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream))
        {
            DataContractSerializer ser = new DataContractSerializer(typeof(List<NodeInfo>));
            {
                writer.WriteStartDocument();
                ser.WriteObject(writer, locations.ToList());
            }
            stream.Close();
        }
    }
}

PUT请求似乎正在起作用。但是当我尝试接收此集合(GET请求)时,我在反序列化时有一个例外:Unexpected end of file... 在调试器中,字符串末尾XML并非所有标记。我认为编写线程(服务器)没有完成。我该如何解决它?我也有几个问题。此实现是否线程安全?如果我使用并发集合,则不需要使用信号量或其他同步?

谢谢!

线程安全服务器

看起来您过早地关闭了输出流。在GetRequestProcess(),只需删除对stream.Close()的调用即可。这将允许编写器在流关闭时刷新到流。只要正确释放对象(如下所示),就不需要显式关闭任何内容。

至于你的其他问题,如果你在线程安全工作时遇到具体问题,我建议你发布一个不同的问题,不要让所有的 I/O 代码混淆事情。如果您只是希望有人审查您的代码,请使用 Stack Exchange 上的代码审查站点。

相关文章: