线程安全的服务器

时间:2014-11-15 23:30:39

标签: c# asynchronous httpclient

我尝试实现多线程服务器。很少有客户端(< 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字符串末尾没有所有标记。我认为写线程(服务器)没有完成。我该如何解决? 我也几乎没有问题。这个实现是否是线程安全的?如果我使用并发集合,我不需要使用信号量或其他同步?

非常感谢!

1 个答案:

答案 0 :(得分:1)

看起来您过早地关闭了输出流。在GetRequestProcess()中,只需删除对stream.Close()的调用即可。这将让作者在关闭时刷新到流。只要您正确处理对象(就像您在这里一样),就不需要显式关闭任何东西。

至于你提出的其他问题,我建议你发布一个不同的问题,如果你遇到特定问题让线程安全工作,那么所有的I / O代码都不会混淆。如果您只是想让某人查看您的代码,请使用Stack Exchange上的Code Review网站。