Close() private method

private Close ( ) : void
return void
示例#1
0
        /// <summary>
        /// This method sends a PDU on the socket session
        /// </summary>
        /// <param name="pdu"></param>
        /// <returns></returns>
        internal bool SendPdu(SmppPdu pdu)
        {
            if (sock_.IsConnected)
            {
                try
                {
                    FireEvent(EventType.PostProcessPdu, new SmppEventArgs(this, pdu));
                }
                catch
                {
                }

                try
                {
                    SmppByteStream bs = new SmppByteStream();
                    pdu.Serialize(new SmppWriter(bs, this.version_));
                    sock_.Send(bs.GetBuffer());
                    return(true);
                }
                catch (System.Net.Sockets.SocketException ex)
                {
                    sock_.Close(true);
                    FireEvent(EventType.SessionDisconnected, new SmppDisconnectEventArgs(this, ex));
                }
            }
            return(false);
        }
示例#2
0
 private void TransferSingleTaskSmallFile(FileTask task, TransferType taskType)
 {
     try
     {
         SocketClient client = SocketFactory.GenerateConnectedSocketClient(task, 1);
         if (taskType == TransferType.Upload)
         {
             int    pt           = 0;
             byte[] headerBytes  = BytesConverter.WriteString(new byte[4], task.RemotePath, ref pt);
             byte[] contentBytes = File.ReadAllBytes(task.LocalPath);
             byte[] bytes        = new byte[headerBytes.Length + contentBytes.Length];
             Array.Copy(headerBytes, 0, bytes, 0, headerBytes.Length);
             Array.Copy(contentBytes, 0, bytes, headerBytes.Length, contentBytes.Length);
             client.SendBytes(SocketPacketFlag.UploadRequest, bytes);
             client.ReceiveBytesWithHeaderFlag(SocketPacketFlag.UploadAllowed, out byte[] recvBytes);
             client.Close();
         }
         else
         {
             client.SendBytes(SocketPacketFlag.DownloadRequest, task.RemotePath);
             client.ReceiveBytesWithHeaderFlag(SocketPacketFlag.DownloadAllowed, out byte[] bytes);
             client.Close();
             File.WriteAllBytes(task.LocalPath, bytes);
         }
         this.Record.CurrentFinished = task.Length;
         task.Status = FileTaskStatus.Success;
     }
     catch (Exception ex)
     {
         task.Status = FileTaskStatus.Failed;
         System.Windows.Forms.MessageBox.Show(ex.Message);
     }
 }
示例#3
0
        private void connectCarToWifi()
        {
            WifiConn msg;

            if (requirePassword)
            {
                msg = new WifiConn(user.ID, entryCarName.Text, network.SSID, entryWifiPass.Text);
            }
            else
            {
                msg = new WifiConn(user.ID, entryCarName.Text, network.SSID);
            }

            SocketClient client;

            try
            {
                client = new SocketClient(Constants.CarAccessPointIP, Constants.CarAccessPointPort);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Unable to create UDP client: " + e.Message);
            }

            client.SetRecvTimeout(15000);
            int  attempts  = 0;
            bool firstSend = true;

            while (attempts < 10)
            {
                client.Send(msg);

                Message resp = client.Receive();

                if (firstSend)
                {
                    firstSend = false;
                    client.SetRecvTimeout(2000);
                }

                if (resp is Error error)
                {
                    client.Close();
                    throw new ArgumentException(error.ErrorMsg);
                }

                if (resp is Ack)
                {
                    client.Close();
                    return;
                }

                attempts++;
            }

            client.Close();
            throw new ServerUnreachableException();
        }
示例#4
0
    /// <summary>
    /// 4秒没连接上socket,重连
    /// </summary>
    /// <returns></returns>
    private IEnumerator ConnectTimer()
    {
        yield return(new WaitForSeconds(_totalReconnectTime / _reconnectTimes));

        LogUtil.Log(string.Format("连接时间超过{0}秒!!!socket连接失败,关闭socket,重新连接。", _totalReconnectTime / _reconnectTimes));

        OnConnectFailedCallback();
        _socketClient.Close();
        Reconnect();
    }
示例#5
0
        async private Task RefreshCars(StackLayout carList, RefreshView refresh)
        {
            SocketClient client;

            try
            {
                client = new SocketClient(Constants.ServerIP, Constants.ServerPort);
            }
            catch (Exception e)
            {
                refresh.IsRefreshing = false;
                await DisplayAlert("Car Refresh", e.Message, "OK");

                return;
            }

            client.SetRecvTimeout(Constants.TIMEOUT);

            int attempts = 0;

            while (attempts < Constants.MAX_ATTEMPTS)
            {
                client.Send(new GetCars(this._User.ID));

                Message resp = client.Receive();

                if (resp is Error error)
                {
                    client.Close();
                    refresh.IsRefreshing = false;
                    await DisplayAlert("Car Refresh", error.ErrorMsg, "OK");

                    return;
                }

                if (resp is Ack ack && ack.Cars != null)
                {
                    client.Close();
                    BindableLayout.SetItemsSource(carList, ack.Cars);
                    refresh.IsRefreshing = false;
                    return;
                }

                attempts++;
            }

            client.Close();
            refresh.IsRefreshing = false;
            await DisplayAlert("Car Refresh", "Server is unreachable. Try again later.", "OK");

            return;
        }
示例#6
0
        private void OnCarSelect(object sender, EventArgs args)
        {
            Button carBtn = (Button)sender;

            int carID = (int)carBtn.CommandParameter;

            SocketClient client;

            try
            {
                client = new SocketClient(Constants.ServerIP, Constants.ServerPort);
            }
            catch (Exception e)
            {
                DisplayAlert("Car Link", e.Message, "OK");
                return;
            }

            client.SetRecvTimeout(Constants.TIMEOUT);

            int attempts = 0;

            while (attempts < Constants.MAX_ATTEMPTS)
            {
                client.Send(new Link(carID, this._User.ID));

                Message resp = client.Receive();

                if (resp is Error error)
                {
                    client.Close();
                    DisplayAlert("Car Link", error.ErrorMsg, "OK");
                    return;
                }

                if (resp is Ack)
                {
                    client.Close();
                    Navigation.PushAsync(new VideoStreamPage(carID));
                    return;
                }

                attempts++;
            }

            client.Close();
            DisplayAlert("Car Link", "Server is unreachable. Try again later.", "OK");
            return;
        }
示例#7
0
文件: Comm.cs 项目: fialot/Logger
        /// <summary>
        /// Close connection
        /// </summary>
        public void Close()
        {
            try
            {
                switch (OpenInterface)
                {
                case interfaces.COM:
                    SP.ReadExisting();
                    SP.Close();
                    break;

                case interfaces.TCPClient:
                case interfaces.TCPServer:
                case interfaces.Udp:
                    SocketClient.Close();
                    break;

                default:
                    break;
                }
            }
            catch (Exception)
            {
            }
            OpenInterface = interfaces.None;
        }
示例#8
0
    /// <summary>
    /// 实例化socket类
    /// </summary>
    public static SocketClient SocketConnect(string RemoteIP, int RemotePort, string cn)
    {
        SocketClient     sc    = null;
        SocketClientType _type = GetSocketClientType(cn);

        if (!SocketDic.TryGetValue(_type, out sc))
        {
            SocketDic[_type] = new SocketClient(RemoteIP, RemotePort, cn);
            sc = SocketDic[_type];
        }
        else if (sc.ip == RemoteIP && sc.port == RemotePort)
        {
            if (!sc.IsConnected)
            {
                sc.StartInitSocket();
            }
        }
        else
        {
            sc.Close();
            SocketDic[_type] = new SocketClient(RemoteIP, RemotePort, cn);
            sc = SocketDic[_type];
        }
        return(sc);
    }
示例#9
0
 private void CloseFunc(SocketClient client)
 {
     //if (client.IsAlive)
     //{
     client.Close();
     //}
 }
示例#10
0
        private void Send_Click(object sender, RoutedEventArgs e)
        {
            ClearLog();

            if (settings.isConnected && ValidateInput())
            {
                SocketClient client = settings.socketClient;

                /*
                 * Log(String.Format("Connecting to server '{0}' over port {1} (echo ...", textRemoteHost.Text, ECHO_PORT), true);
                 * string result = client.Connect(settings.ServerSetting, settings.PortSetting);
                 * Log(result, false);
                 */

                Log(String.Format("Sending '{0}' to server {1}...", txtInput.Text, settings.ServerSetting), true);
                string result = client.Send(txtInput.Text);
                Log(result, false);

                Log("requesting Receive...", true);
                result = client.Receive();
                Log(result, false);
                client.Close();
            }

            else
            {
                MessageBox.Show("please enter text to server or a valid remote host ");
            }
        }
示例#11
0
 /// <summary>
 /// 获取 server 文件列表
 /// </summary>
 /// <returns>请求是否成功 bool 值</returns>
 private Task <bool> ListFiles()
 {
     return(Task.Run(() => {
         try
         {
             Logger.Log("Requesting directory : " + RemoteDirectory, LogLevel.Info);
             SocketClient client = SocketFactory.GenerateConnectedSocketClient();
             client.SendBytes(SocketPacketFlag.DirectoryRequest, RemoteDirectory);
             client.ReceiveBytesWithHeaderFlag(SocketPacketFlag.DirectoryResponse, out byte[] recv_bytes);
             this.fileClasses = SocketFileInfo.BytesToList(recv_bytes);
             client.Close();
             this.Dispatcher.Invoke(() => {
                 this.ListViewFile.ItemsSource = this.fileClasses;
                 this.TextRemoteDirectory.Text = RemoteDirectory;
             });
             return true;
         }
         catch (Exception ex)
         {
             string msg = "Requesting remote directory \"" + RemoteDirectory + "\" failure : " + ex.Message;
             Logger.Log(msg, LogLevel.Warn);
             System.Windows.Forms.MessageBox.Show(msg);
             return false;
         }
     }));
 }
示例#12
0
 void OnApplicationQuit()
 {
     if (network.IsConnected)
     {
         network.Close(true);
     }
 }
示例#13
0
        /// <summary>
        /// This method is invoked when a new inbound socket hits our server.  We will create a new
        /// SMPP session object to manage the socket and begin communicating with the ESME session.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected void OnStartSession(object sender, SocketEventArgs args)
        {
            ConnectEventArgs connEv = (ConnectEventArgs)args;
            SocketClient     scNew  = connEv.Client;

            // Create a new SMPP session to manage this connection.
            SmscSession newSession = new SmscSession(this, scNew, systemid_);

            // Back-link the session
            scNew.Tag = newSession;

            // Notify anyone who wants to know
            SmppConnectEventArgs sce = new SmppConnectEventArgs(scNew.Address, newSession);

            if (OnNewSession != null)
            {
                OnNewSession(this, sce);
            }
            if (!sce.AllowConnection)
            {
                scNew.Close(true);
            }
            else
            {
                scNew.OnEndSession += OnEndClientSession;
                lock (clients_)
                {
                    clients_.Add(newSession);
                }
            }
        }
示例#14
0
 /// <summary>
 /// 析构函数
 /// </summary>
 public void Close()
 {
     client.Close();
     server.Stop();
     threadOut.Stop();
     threadIn.Stop();
 }
示例#15
0
 private void UploadSingleTaskDirectory(FileTask task)
 {
     /// 请求 server 端创建目录
     try
     {
         SocketClient client      = SocketFactory.GenerateConnectedSocketClient(task, 1);
         int          pt          = 0;
         byte[]       headerBytes = BytesConverter.WriteString(new byte[4], task.RemotePath, ref pt);
         client.SendBytes(SocketPacketFlag.CreateDirectoryRequest, headerBytes);
         client.ReceiveBytesWithHeaderFlag(SocketPacketFlag.CreateDirectoryAllowed, out byte[] recvBytes);
         client.Close();
     }
     catch (Exception)
     {
         task.Status = FileTaskStatus.Denied;
         return;
     }
     /// 更新 TaskList, 重新定位当前任务
     UpdateTasklist(this,
                    new UpdateUIInvokeEventArgs(new Action(() => {
         lock (this.Record)
         {
             FileTask father_task = Record.CurrentTask;
             int bias             = Record.CurrentTaskIndex;
             this.Record.RemoveTaskAt(Record.CurrentTaskIndex);
             List <FileTask> tasks_son = GetUploadTasksInDirectory(father_task);
             for (int i = 0; i < tasks_son.Count; ++i)
             {
                 FileTask task_son = tasks_son[i];
                 UpdateTaskLength(task_son);
                 this.Record.InsertTask(bias + i, task_son);
             }
         }
     })));
 }
示例#16
0
 public void Disconnect()
 {
     mSocketClient.OnConnected      -= OnConnected;
     mSocketClient.OnDisconnected   -= OnDisconnected;
     mSocketClient.OnReceiveMessage -= OnReceiveMessage;
     mSocketClient.Close();
 }
示例#17
0
 public void Close()
 {
     if (SC != null)
     {
         SC.Close();
     }
 }
示例#18
0
 public void Close()
 {
     if (m_instance != null)
     {
         m_instance = null;
     }
     m_SocketClient?.Close();
 }
示例#19
0
    public static void Main(String[] args)
    {
        SocketClient.StartClient();
        Process process = new Process();

        process.ReadAndWrite();
        SocketClient.Close();
    }
示例#20
0
 private void DeleteFunc(SocketClient client)
 {
     //if (client.IsAlive)
     //{
     //    client.Close();
     //}
     client.Close();
     LstSocketClt.Remove(client);
 }
示例#21
0
        void RunQueueList()
        {
            try
            {
                if (UserMaskList.Count > 0) //如果列队数量大于0
                {
Re:
                    string userkey;

                    if (UserMaskList.TryDequeue(out userkey)) //挤出一个用户ID
                    {
                        if (userkey == Key)
                        {
                            goto Re;
                        }

                        SocketClient client = new SocketClient();                        //建立一个 SOCKET客户端
Pt:
                        IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, BindPort++); //绑定当前端口

                        if (BindPort >= 60000)
                        {
                            BindPort = 1000;
                        }

                        try
                        {
                            client.Sock.Bind(endpoint); //如果无法绑定此端口 那么换个端口
                        }
                        catch
                        {
                            goto Pt;
                        }

                        if (client.Connect(Host, RegIpPort)) //连接注册服务器端口
                        {
                            BufferFormat tmp = new BufferFormat(100);
                            tmp.AddItem(Key);
                            tmp.AddItem(BindPort);
                            client.Send(tmp.Finish());

                            System.Threading.Thread.Sleep(50); //等待 50毫秒

                            BufferFormatV2 tmp2 = new BufferFormatV2((int)PCMD.CONN);
                            tmp2.AddItem(userkey);
                            Mainclient.Send(tmp2.Finish());
                            client.Close();//关闭客户端
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogOut.LogIn(e.ToString(), ActionType.Error);
            }
        }
示例#22
0
    public static void RemoveSocket(SocketClientType _type)
    {
        SocketClient sc = null;

        if (!SocketDic.TryGetValue(_type, out sc))
        {
            SocketDic.Remove(_type);
            sc.Close();
        }
    }
示例#23
0
 public void Close()
 {
     WebClient.Close();
     SocketClient.Close();
     if (Proxy.Instance == null)
     {
         Console.WriteLine("dsaabadzxzxzxzxzxzx");
     }
     Proxy.Instance.Remove(Name);
 }
示例#24
0
        private Dictionary <string, string> getWiFiList()
        {
            GetSSID msg = new GetSSID();

            SocketClient client;

            try
            {
                client = new SocketClient(Constants.CarAccessPointIP, Constants.CarAccessPointPort);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Unable to create UDP client: " + e.Message);
            }

            client.SetRecvTimeout(5000); // TODO: USE CONSTANT
            int attempts = 0;

            while (attempts < 3) // TODO: USE CONSTANT
            {
                client.Send(msg);

                Message resp = client.Receive();

                if (resp is Error error)
                {
                    client.Close();
                    throw new ArgumentException(error.ErrorMsg);
                }

                if (resp is Ack ack && ack.Networks != null)
                {
                    client.Close();
                    return(ack.Networks);
                }

                attempts++;
            }

            client.Close();
            throw new ServerUnreachableException();
        }
示例#25
0
 public void ReConnect()
 {
     if (netStatus == NetStatus.None || netStatus == NetStatus.OnReconnect || netStatus == NetStatus.WaitToDlgLogin)
     {
         return;
     }
     netStatus = NetStatus.OnReconnect;
     _socket.Close();   //弱网中,到断线重连了之后,主动断socket
     _reConnect.Call(); //通知lua层断线重连
     SendConnect(GameMain.Inst.loginHost, GameMain.Inst.port);
 }
 public void Close(string reason)
 {
     if (_client != null)
     {
         _client.Close(reason);
         lock (LockObject)
         {
             _respQueue.Clear();
             NetRespEvent = null;
         }
     }
 }
示例#27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="task"></param>
        private void TransferSingleTaskBigFile(FileTask task)
        {
            /// 请求 server 端打开文件, 并获取 FileStreamId
            task.FileStreamId = GetFileStreamId(task);
            if (task.FileStreamId == -1)
            {
                task.Status = FileTaskStatus.Failed;
                Record.CurrentTaskIndex++;
                return;
            }


            /// 创建本地 FileStream
            localFileStream = new FileStream(task.LocalPath, FileMode.OpenOrCreate,
                                             task.Type == TransferType.Upload ? FileAccess.Read : FileAccess.Write);


            /// 运行下载子线程
            FileTaskStatus result = RunTransferSubThreads(task);

            /// 结束 Transfer, 关闭 FileStream
            localFileStream.Close();
            localFileStream = null;

            /// 请求server端关闭并释放文件
            try
            {
                SocketClient sc = SocketFactory.GenerateConnectedSocketClient(task, 1);
                if (task.Type == TransferType.Upload)
                {
                    sc.SendBytes(SocketPacketFlag.UploadPacketRequest, new byte[1], task.FileStreamId, -1);
                }
                else
                {
                    sc.SendHeader(SocketPacketFlag.DownloadPacketRequest, task.FileStreamId, -1);
                }
                sc.Close();
            }
            catch (Exception ex)
            {
                Logger.Log("Transfer finished. But server FileStream not correctly closed. " + ex.Message, LogLevel.Warn);
            }

            /// 判断从子线程退出返回原因是否是 Pause
            if (IsStopDownloading)
            {
                task.Status = FileTaskStatus.Pause;
            }
            else
            {
                task.Status = result;
            }
        }
示例#28
0
 public void CloseConnect(SocketClient c, bool remove=false)
 {
     if (c == null)
     {
         return;
     }
     log.InfoFormat("Device {0} closed.", c.IpAddr );
     c.Close();
     if (remove)
     {
         SocketClient removed;
         _connections.TryRemove(c.IpAddr, out removed);
     }
 }
示例#29
0
 static int Close(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         SocketClient obj = (SocketClient)ToLua.CheckObject <SocketClient>(L, 1);
         obj.Close();
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
示例#30
0
    public static void RemoveSocket(SocketClient rsc)
    {
        if (rsc == null)
        {
            return;
        }

        rsc.Close();
        if (SocketDic.ContainsKey(rsc.mSocketClientType))
        {
            SocketDic.Remove(rsc.mSocketClientType);
        }
        rsc = null;
    }
示例#31
0
        static void Main(string[] args)
        {
            //创建客户端对象,默认连接本机127.0.0.1,端口为12345
            SocketClient client = new SocketClient(12345);

            //绑定当收到服务器发送的消息后的处理事件
            client.HandleRecMsg = new Action <byte[], SocketClient>((bytes, theClient) =>
            {
                string msg = Encoding.UTF8.GetString(bytes);
                Console.WriteLine($"收到消息:{msg}");
            });

            //绑定向服务器发送消息后的处理事件
            client.HandleSendMsg = new Action <byte[], SocketClient>((bytes, theClient) =>
            {
                string msg = Encoding.UTF8.GetString(bytes);
                Console.WriteLine($"向服务器发送消息:{msg}");
            });

            //开始运行客户端
            client.StartClient();

            while (true)
            {
                Console.WriteLine("输入:quit关闭客户端,r重试连接服务器,输入其它消息发送到服务器");
                string str = Console.ReadLine();
                if (str == "r")
                {
                    client.StartClient();
                    break;
                }
                if (str == "quit")
                {
                    client.Close();
                    break;
                }
                else
                {
                    if (client.IsConnectToServer)
                    {
                        client.SendData(str);
                    }
                    else
                    {
                        Console.WriteLine("未连接到服务器");
                    }
                }
            }
        }