0

我的 Socketasync 应用程序有问题,我有一个服务器和一个客户端(下面的代码),通信的一切都很好,除非服务器应用程序关闭,然后客户端无法重新连接。如果我重新启动客户端,它完全没有问题,重新连接,但它必须重新启动。所以我的问题是如何修改此代码,以帮助它重新连接而无需重新启动它自己的应用程序。

这是连接代码!

    public Client()
    {
        try
        {

            this.ip = ini.GetFromIni("CONFIG", "IP");
            this.port = ini.GetFromIni("CONFIG", "PORT");
            data = new byte[60000];
            receiveBuffer = new byte[60000];

            this.hostEndPoint = new IPEndPoint(IPAddress.Parse(this.ip), Convert.ToInt32(port));
            this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            // Instantiates the endpoint and socket.

            startTimer = new System.Timers.Timer();
            startTimer.Elapsed += new ElapsedEventHandler(startSendLoop);
            startTimer.Interval = 1000;
            startTimer.Start();
            sendTimer = new System.Timers.Timer();
            sendTimer.Elapsed += new ElapsedEventHandler(sendloop);
            sendTimer.Interval = 500;
            sendTimer.Start();

        }
        catch (Exception e)
        {
        }
    }   

    public void startSendLoop(object sender, ElapsedEventArgs e)
    {
        try
        {
            startTimer.Interval = 10000;
            startTimer.Enabled = false;
            if (!this.clientSocket.Connected)
            {
                this.hostEndPoint = new IPEndPoint(IPAddress.Parse(this.ip), Convert.ToInt32(port));
                this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                if (connectArgs != null)
                    connectArgs.Dispose();
                connectArgs = new SocketAsyncEventArgs();

                connectArgs.UserToken = this.clientSocket;
                connectArgs.RemoteEndPoint = this.hostEndPoint;
                connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);

                clientSocket.ConnectAsync(connectArgs);
                bool test = autoConnectEvent.WaitOne(5000);

                gotData = true;
                lastTime = DateTime.Now;

            }
            startTimer.Enabled = true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

¨

如果有人想查看更多代码......不直接链接到连接。

    private void OnConnect(object sender, SocketAsyncEventArgs e)
    {

        autoConnectEvent.Set();

        // Set the flag for socket connected.
        this.connected = (e.SocketError == SocketError.Success);
    }

    private void OnSend(object sender, SocketAsyncEventArgs e)
    {
        // Signals the end of send.
        sendSuccess = true;
        autoSendReceiveEvents[ReceiveOperation].Set();

        if (e.SocketError == SocketError.Success)
        {
            if (e.LastOperation == SocketAsyncOperation.Send)
            {
                // Prepare receiving.
                //Socket s = e.UserToken as Socket;

                for (int i = 0; i < receiveBuffer.Length; i++)
                {
                    if (receiveBuffer[i] != 0)
                        receiveBuffer[i] = 0;
                    else
                        break;
                }
                e.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
                e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
                clientSocket.ReceiveAsync(e);
                //sendloop();
            }
        }
        else
        {
            this.ProcessError(e);
        }
    }

    private void OnReceive(object sender, SocketAsyncEventArgs e)
    {
        try
        {
            while (true)
            {
                if (this.canReceive)
                {

                    canReceive = false;
                    string stringData;
                    int recv = 0;

                    for (int i = 0; i < e.Buffer.Length; i++)
                    {
                        if (e.Buffer[i] != 0)
                            recv++;
                        else
                            break;
                    }

                    if (recv > 0)
                    {
                        Console.WriteLine(recv.ToString());
                        int count = 0;
                        for (int i = 0; i < data.Length; i++)
                        {
                            if (data[i] != 0)
                                count++;
                            else
                                break;
                        }

                        e.Buffer.CopyTo(data, count);
                        //currentData = Encoding.UTF8.GetString(e.Buffer, 0, recv);
                        lastTime = DateTime.Now;
                        gotData = true;
                        if ((byte)data[count + recv - 1] == (byte)255)
                        {
                            int cnt = -1;
                            for (int i = 0; i < count + recv; i++)
                            {
                                if (data[i] == (byte)254)
                                {
                                    cnt = i;
                                    break;
                                }
                            }
                            int nr = (count + recv) - cnt - 2;
                            byte[] tmp = new byte[nr];

                            for (int i = 0; i < nr; i++)
                            {
                                tmp[i] = data[cnt + i + 1];
                            }
                            string crc = Encoding.Default.GetString(tmp);
                            stringData = Encoding.Default.GetString(data, 0, cnt);
                            MsgStruct msgs = new MsgStruct(stringData);
                            msgs.setCrc(crc);
                            todo.Add(msgs);
                            for (int i = 0; i < data.Length; i++)
                            {
                                if (data[i] != 0)
                                    data[i] = 0;
                                else
                                    break;
                            }
                            allreadyGot = false;
                            handleToDo();

                            // Signals the end of receive.

                        }

                    }
                    autoSendReceiveEvents[SendOperation].Set();
                    Socket s = e.UserToken as Socket;
                    canReceive = true;
                    break;
                }
                else
                {
                    Thread.Sleep(10);
                }
            }
        }
        catch (Exception ex)
        {
            canReceive = true;
        }

    }

    private void ProcessError(SocketAsyncEventArgs e)
    {
        Socket s = e.UserToken as Socket;
        if (s.Connected)
        {
            // close the socket associated with the client
            try
            {
                s.Shutdown(SocketShutdown.Both);
            }
            catch (Exception)
            {
                // throws if client process has already closed
            }
            finally
            {
                if (s.Connected)
                {
                    s.Close();
                }
            }
        }

        // Throw the SocketException
        //throw new SocketException((Int32)e.SocketError);
    }

    public void sendloop(object sender, ElapsedEventArgs e)
    {

        try
        {
            if (this.clientSocket.Connected)
            {
                sendTimer.Enabled = false;

                bool waitExtra = false;

                DateTime tmpDate = lastTime.AddSeconds(30);
                if (DateTime.Now > tmpDate && tmpDate != DateTime.MinValue)
                {
                    gotData = false;
                }

                if(sendSuccess)
                {
                    canUseBuffert = false;
                    if (msgHand.gotMsg() && data[0] == 0)
                    {
                        if (msgHand.getNextMsg() != null && msgHand.getNextMsg().getMsg().Length != 0)
                        {
                            byte[] ba = Encoding.Default.GetBytes(msgHand.getNextMsg().getMsg());

                            if (msgHand.getNextMsg().getCrc() == "")
                            {
                                ulong tmp = CRC.calc_crc(ba, ba.Length);
                                msgHand.getNextMsg().setCrc(tmp.ToString("X"));
                            }

                            if (msgHand.getNextMsg().canSendByTimeout())
                            {
                                string crcStr = "?" + msgHand.getNextMsg().getCrc() + "?";
                                byte[] bb = Encoding.Default.GetBytes(crcStr);
                                crcStr = Encoding.Default.GetString(bb);
                                byte[] fullMsg = new byte[ba.Length + bb.Length];
                                bb[0] = 254;
                                bb[bb.Length - 1] = 255;

                                ba.CopyTo(fullMsg, 0);
                                bb.CopyTo(fullMsg, ba.Length);
                                string s = System.Text.Encoding.Default.GetString(fullMsg);

                                completeArgs = new SocketAsyncEventArgs();
                                completeArgs.SetBuffer(fullMsg, 0, fullMsg.Length);
                                completeArgs.UserToken = this.clientSocket;
                                completeArgs.RemoteEndPoint = this.hostEndPoint;
                                completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
                                sendSuccess = false;
                                // Start sending asyncronally.
                                clientSocket.SendAsync(completeArgs);

                                // Wait for the send/receive completed.
                                //AutoResetEvent.WaitAll(autoSendReceiveEvents);

                                // Return data from SocketAsyncEventArgs buffer.
                                //stm.Write(fullMsg, 0, fullMsg.Length);

                                if (!msgHand.getNextMsg().isAckNeeded())
                                    msgHand.removeNextMsgs();
                            }
                        }
                    }
                    else
                    {

                        waitExtra = true;
                        byte[] bba = Encoding.Default.GetBytes("X");
                        completeArgs = new SocketAsyncEventArgs();
                        completeArgs.SetBuffer(bba, 0, bba.Length);
                        completeArgs.UserToken = this.clientSocket;
                        completeArgs.RemoteEndPoint = this.hostEndPoint;
                        completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
                        sendSuccess = false; //Dessa ska in även i den andra applikationen
                        // Start sending asyncronally.
                        clientSocket.SendAsync(completeArgs);

                        // Wait for the send/receive completed.
                        //AutoResetEvent.WaitAll(autoSendReceiveEvents);
                    }
                }
                canUseBuffert = true;
                //if (!clientSocket.Connected && !gotData)
                    //Disconnect();

            }

            sendTimer.Enabled = true;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
            sendTimer.Enabled = true;
        }
    }

    internal void Disconnect()
    {

        clientSocket.Disconnect(true);
    }

    public void Dispose()
    {
        autoConnectEvent.Close();
        autoSendReceiveEvents[SendOperation].Close();
        autoSendReceiveEvents[ReceiveOperation].Close();
        if (this.clientSocket.Connected)
        {
            this.clientSocket.Close();
        }
    }
    public void handleToDo()
    {
         //handle msg
    }
4

0 回答 0