简体   繁体   中英

C# TCP/IP Server showing as not connected

For some reason my server is showing as disconnected when the client seems to have at least connected to the open port and is sending packets down it.

 clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);


            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, Convert.ToInt32(PORT));

            //Bind and listen 
            clientSocket.Bind(ipEndPoint);
            clientSocket.Listen(5);

            //Accept incoming 
            clientSocket.BeginAccept(new AsyncCallback(OnAccept), null);

Then after this here is my OnAccept method.

 private void OnAccept(IAsyncResult ar)
    {
        try
        {
            clientSocket.EndAccept(ar);



            if (clientSocket.Connected == true)
            {
                clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket);
            }
        }
        catch (Exception ex)
        {
            log.Log(ex.ToString(), 2);
        }
    }

I am using an out of the box client to connect (something im using for testing purposes) however when I start a connection to listen and click "connect" on the client. The client turns to "Connected" state and starts to send packets. However that "if (clientSocket.Connected == true)" statement always fails, even after running a breakpoint on it so its not a timing issue.

Any help and ideas would be greatly appreciated.

So it seems that when im using the async and listening in the way I am, I have to accept on that socket a new socket.

Socket clientSocket2 = clientSocket.EndAccept(ar);

Then gets the connection on cliientSocket2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM