开发者

Help with Exception with TCPListener

I keep getting the following exception when a client connects to the TCPListener.

Exception:

System.ObjectDisposedException: Cannot access a disposed object.

Object name: 'System.Net.Sockets.NetworkStream'.

at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

at Test.Server.ProcessClient(Object client, Object clientId)


Server.cs

public class Server
{
    private TcpListener tcpListener;
    private Thread listenThread;

    public event EventHandler<EventLogArgs> EventLog;

    public Server()
    {
        // Startup Code
        ThreadPool.SetMinThreads(50, 50);
    }

    void UpdateEventLog(EventLogArgs e)
    {
        if (EventLog != null)
        {
            EventLog(this, e);
        }
    }

    public void Start(string ip, int port_num)
    {
        Globals.listen = true;

        Int32 port = port_num;
        IPAddress address = IPAddress.Parse(ip);

        this.tcpListener = new TcpListener(address, port);

        Socket listenerSocket = this.tcpListener.Server;

        LingerOption lingerOption = new LingerOption(true, 10);
        listenerSocket.SetSocketOption(SocketOptionLevel.Socket,
                          SocketOptionName.Linger,
                          lingerOption);

        this.listenThread = new Thread(ListenForClients);
        this.listenThread.Start();

        UpdateEventLog(new EventLogArgs("Started server..."));
    }

    public void Stop()
    {
        Globals.listen = false;
        UpdateEventLog(new EventLogArgs("Stop server request sent..."));
    }

    private void ListenForClients()
    {
        this.tcpListener.Start();

        while (Globals.listen)
        {
            if (!this.tcpListener.Pending())
            {
                // This is so we can stop the server.
                Thread.Sleep(25); // choose a number (in milliseconds) that makes sense
                continue; // skip to next iteration of loop
            }

            //blocks until a client has connected to the server
            TcpClient client = this.tcpListener.AcceptTcpClient();

            Globals.clientRequests++;
            int clientRequest = Globals.clientRequests;
            UpdateEventLog(new EventLogArgs("(" + Globals.clientRequests + ") Client connected...\r\n"));

            ThreadPool.QueueUserWorkItem(o => ProcessClient(client, clientRequest));
        }

        UpdateEventLog(new EventLogArgs("Stopped server!"));
        this.tcpListener.Stop();
    }

    private void ProcessClient(object client, object clientId)
    {
        TcpClient tcpClient = (TcpClient)client;
        int clientRequestId = (int)clientId;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] clientRequestRaw = new byte[1024];
        int bytesRead;

        UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") Process client request..."));

        while (true)
        {
            bytesRead = 0;
            try
            {
                //blocks until a client sends a message
                bytesRead =开发者_运维知识库 clientStream.Read(clientRequestRaw, 0, 512);
            }
            catch
            {
                //a socket error has occured
                UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") SOCKET ERROR\r\n\r\n" + e));
                break;
            }
            if (bytesRead == 0)
            {
                //the client has disconnected from the server
                UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") Client disconnected from server, nothing sent."));
                break;
            }

            //message has successfully been received.
            ASCIIEncoding encoder = new ASCIIEncoding();
            string clientRequest = encoder.GetString(clientRequestRaw, 0, bytesRead);

            string[] cmd;
            string success;
            Dictionary<string, string> headers = new Dictionary<string, string>();
            Dictionary<string, string> contents = new Dictionary<string, string>();

            if (clientRequest.Length == 0)
            {
                return;
            }

            // Parse HTTP request
            Parse Parse = new Parse();
            Parse.HTTPRequest(clientRequest, out success, out cmd, out headers, out contents);

            string response;
            if (success == "TRUE")
            {
                response = "HTTP/1.1 200 OK\r\n\r\nHello World!\r\n";
            }
            else
            {
                response = "HTTP/1.1 200 OK\r\n\r\nHello Error!\r\n";
            }


            ResponseToClient(client, response);
            clientStream.Close();

            UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") Server response...\r\n\r\n" + response));
        }

        tcpClient.Close();

        UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") Client disconnected."));
    }

    private void ResponseToClient(object client, string response)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();
        ASCIIEncoding encoder = new ASCIIEncoding();
        byte[] buffer = encoder.GetBytes(response);

        clientStream.Write(buffer, 0, buffer.Length);
        clientStream.Flush();            
    }
}

The Server class is started from the main thread like so:

this.server = new Server();
this.server.EventLog += new EventHandler<EventLogArgs>(UpdateEventLog);
ThreadPool.QueueUserWorkItem(o => this.server.Start("127.0.0.1", 3000));

What am I doing wrong here?


I have taken the while loop out from the ProcessClient() method and this seems to have fixed the problem. Thanks anyway.

private void ProcessClient(object client, object clientId)
{
    TcpClient tcpClient = (TcpClient)client;
    int clientRequestId = (int)clientId;
    NetworkStream clientStream = tcpClient.GetStream();

    byte[] clientRequestRaw = new byte[1024];
    int bytesRead;

    UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") Process client request..."));

    while (true)
    {
        bytesRead = 0;

        try
        {
            //blocks until a client sends a message
            bytesRead = clientStream.Read(clientRequestRaw, 0, 512);
        }
        catch (Exception e) 
        {
            //a socket error has occured
            UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") SOCKET ERROR\r\n\r\n" + e));
            break;
        }

        if (bytesRead == 0)
        {
            //the client has disconnected from the server
            UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") Client disconnected from server, nothing sent."));
            break;
        }

        //message has successfully been received.
        ASCIIEncoding encoder = new ASCIIEncoding();
        string clientRequest = encoder.GetString(clientRequestRaw, 0, bytesRead);

        string[] cmd;
        string success;
        Dictionary<string, string> headers = new Dictionary<string, string>();
        Dictionary<string, string> contents = new Dictionary<string, string>();

        if (clientRequest.Length == 0)
        {
            return;
        }

        // Parse HTTP request
        Parse Parse = new Parse();
        Parse.HTTPRequest(clientRequest, out success, out cmd, out headers, out contents);

        string response;
        if (success == "TRUE")
        {
            response = "HTTP/1.1 200 OK\r\n\r\nHello World!\r\n";
        }
        else
        {
            response = "HTTP/1.1 200 OK\r\n\r\nHello Error!\r\n";
        }

        ResponseToClient(client, response);

        clientStream.Close();

        UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") Server response...\r\n\r\n" + response));
    }

    tcpClient.Close();

    UpdateEventLog(new EventLogArgs("(" + clientRequestId + ") Client disconnected."));
}


You have to give the network right service.
Write services.msc in run,then find your service. YourService->Properties-> Log On-> Log On as Network


Since you solved your problem I'm just gonna give you two hints:

First of all, do not use the thread pool to make synchronous operations asynchronous. It's a waste of resources. Use the asynchronous methods instead (BeginAccept/EndAccept etc).

Next break your class into multiple classes. One taking care of the server parts only and one taking care of the client parts only. It makes your code a lot easier to follow (even for you :)).


Anyway don't use if (success == "TRUE")!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜