客户端断开连接时关闭套接字,以便可以重用c#

时间:2013-12-09 17:52:16

标签: c# arrays winforms sockets

我有一个聊天室应用程序,它完全正常工作但是当客户端断开连接时,套接字仍然打开,很快就会填充30个插槽,因此没有更多的客户端可以连接,我在黑暗中尝试了一下找到连接的每个套接字客户端的索引ip,当断开连接按钮被调用时断开连接,但我不知道如何实际执行此操作,因为它存储在套接字数组中,而不是存储在数组中。

这是我服务器上要断开套接字/客户端的部分。

 public AsyncCallback pfnWorkerCallBack;
        private Socket m_mainSocket;
        private Socket[] m_workerSocket = new Socket[30];
        private int m_clientCount = 0;
        public System.Net.Sockets.Socket m_currentSocket;
        public byte[] dataBuffer = new byte[1024];
        string NickName;

public void OnDataReceived(IAsyncResult asyn)
    {
        try
        {

            SocketPacket socketData = (SocketPacket)asyn.AsyncState;
            int iRx = 0;
            // Complete the BeginReceive() asynchronous call by EndReceive() method
            // which will return the number of characters written to the stream 
            // by the client
            iRx = socketData.m_currentSocket.EndReceive(asyn);
            char[] chars = new char[iRx + 1];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(socketData.dataBuffer,
                                     0, iRx, chars, 0);
            System.String szData = new System.String(chars);
            string text = (szData);

            string temp = szData.Substring(0, 10);

            if (temp == "Disconnect")
            {

                int bum = szData.Length-12;
               temp = szData.Substring(11, bum);

               int no = // find the index of the ip 

                m_clientCount --;
               ArrayList temparray = new ArrayList();
               temparray.AddRange(m_workerSocket.ToArray());

                temparray.RemoveAt(no);
                temparray.Add(null);

               int i = 0;
               foreach (Socket content in temparray)
                {
                  m_workerSocket[i] = content;
                  i++;
                }

            }
            else
            {
                Object objData = text;
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                for (int i = 0; i < m_clientCount; i++)
                {

                    if (m_workerSocket[i] != null)
                    {
                        if (m_workerSocket[i].Connected)
                        {
                            m_workerSocket[i].Send(byData);
                        }
                    }
                }
                Invoke(new Action(() => richTextBoxSendMsg.AppendText(szData)));
                Invoke(new Action(() => richTextBoxSendMsg.AppendText(Environment.NewLine)));
                // Continue the waiting for data on the Socket
                WaitForData(socketData.m_currentSocket);
            }
        }
        catch (ObjectDisposedException)
        {
            System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
        }


        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }

    }

Disconnect调用的客户端

private void buttonDisconnect_Click(object sender, EventArgs e)
    {
        Object objData = "Disconnect " + GetIP();
        byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
        if (m_clientSocket != null)
        {
            m_clientSocket.Send(byData);

            txtBoxMsg.Clear();
        }
        if (m_clientSocket != null)
        {
            m_clientSocket.Close();
            m_clientSocket = null;
            UpdateControls(false);
        }

    }

我希望这是足够的信息,因为我真的很想知道如何做到这一点.. 感谢您提出任何意见和建设性批评。

1 个答案:

答案 0 :(得分:0)

试试这个:

var clientSocket = (Socket)asyn.AsyncState;
for (int i = 0; i < m_workerSocket.Count(); i++)
{
    if (m_workerSocket[i] == clientSocket)
    {
        var sockets = new List<Socket>(m_workerSocket);
        sockets.RemoveAt(i);
        m_workerSocket = sockets.ToArray();
        break;
    }
}
clientSocket.Close()