Inheritance: IDisposable
コード例 #1
0
 protected virtual void SocketMessageHandler(MySocket sender, Utility.Messages.GiocatoreProntoMessageEventArgs e)
 {
     foreach (Utility.IComponent c in GetComponentsByType(typeof(GestoreSchedeMaster)))
     {
         c.Input(new GestoreGiocatoriMessageEventArgs(sender.RemoteAddress, e));
     }
 }
コード例 #2
0
ファイル: AppManager.cs プロジェクト: jiangboh/CS
        /// <summary>
        /// 发送消息到App
        /// </summary>
        /// <param name="appToKen">App信息</param>
        /// <param name="TypeKeyValue">消息内容</param>
        protected void SendMsg2App(AsyncUserToken appToKen, Msg_Body_Struct TypeKeyValue)
        {
            if (appToKen == null)
            {
                OnOutputLog(LogInfoType.WARN, string.Format("目的设备信息为NULL!"));
                return;
            }

            if (TypeKeyValue.type == ApMsgType.scanner)
            {
                sendAppImsiMsgNum++;
            }

            DeviceServerMsgStruct msgStruct = new DeviceServerMsgStruct();

            msgStruct.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            msgStruct.ApInfo.IP = MsgStruct.NullDevice;

            msgStruct.Body = TypeKeyValue;
            string strJosn = JsonConvert.SerializeObject(msgStruct);

            if (-1 == strJosn.IndexOf(AppMsgType.app_heartbeat_response))
            {
                OnOutputLog(LogInfoType.INFO, string.Format("发送消息({0})给APP[{1}:{2}]!",
                                                            TypeKeyValue.type, appToKen.IPAddress, appToKen.Port), LogCategory.S);
                OnOutputLog(LogInfoType.DEBG, string.Format("消息内容:\n{0}", strJosn), LogCategory.S);
            }

            byte[] buff = System.Text.Encoding.Default.GetBytes(strJosn);

            MySocket.SendMessage(appToKen, buff);
        }
コード例 #3
0
 public bool Authorize()
 {
     MySocket.Connect(IPPoint);
     MySocket.Send(authForm.ToBytes());
     Auth = true;
     return(true);
 }
コード例 #4
0
 public void SendMessage(Data packed_message)
 {
     if (Auth)
     {
         MySocket.Send(packed_message.ToBytes());
     }
 }
コード例 #5
0
ファイル: UserController.cs プロジェクト: yhtsnda/WeChatDemo
        public IHttpActionResult UserLoginScan(ScanLoginModel model)
        {
            ApiServerMsg result = new ApiServerMsg();

            try
            {
                //new空对象
                MySocket        socket    = new MySocket();
                XzyWeChatThread xzy       = new XzyWeChatThread(socket, model.devicename);
                DicSocket       dicSocket = new DicSocket()
                {
                    socket       = socket,
                    weChatThread = xzy,
                    dateTime     = DateTime.Now
                };
                XzyWebSocket._dicSockets.Remove(model.uuid);
                XzyWebSocket._dicSockets.Add(model.uuid, dicSocket);
                while (xzy.ScanQrCode == "")
                {
                    Thread.Sleep(200);
                }
                result.Success = true;
                result.Context = xzy.ScanQrCode;
                return(Ok(result));
            }
            catch (Exception ex)
            {
                result.Success    = false;
                result.ErrContext = ex.Message;
                return(Ok(result));
            }
        }
コード例 #6
0
 protected void SendMsg2Ap(AsyncUserToken apToKen, string type, string buff)
 {
     OnOutputLog(LogInfoType.INFO, string.Format("发送消息({0})给AP[{1}:{2}]!",
                                                 type, apToKen.IPAddress.ToString(), apToKen.Port));
     OnOutputLog(LogInfoType.DEBG, string.Format("消息内容为:\n{0}", buff));
     MySocket.SendMessage(apToKen, buff);
 }
コード例 #7
0
ファイル: AppManager.cs プロジェクト: jiangboh/CS
        /// <summary>
        /// 发送消息到App
        /// </summary>
        /// <param name="appInfo">Ap信息</param>
        /// <param name="stdeviceServerMsgStructr">消息内容</param>
        protected void SendMsg2App(App_Info_Struct appInfo, DeviceServerMsgStruct deviceServerMsgStruct)
        {
            try
            {
                if ((string.IsNullOrEmpty(appInfo.Ip)) || (appInfo.Ip == MsgStruct.NullDevice))
                {
                    OnOutputLog(LogInfoType.INFO, string.Format("目的设备为Null,不向App发送信息!"));
                    return;
                }

                if (deviceServerMsgStruct.Body.type == ApMsgType.scanner)
                {
                    sendAppImsiMsgNum++;
                }

                string strJosn = JsonConvert.SerializeObject(deviceServerMsgStruct);
                byte[] buff    = System.Text.Encoding.Default.GetBytes(strJosn);

                if (appInfo.Ip == MsgStruct.AllDevice)
                {
                    OnOutputLog(LogInfoType.INFO, string.Format("目的设备为All,向所有App发送信息!"));
                    //HashSet<AsyncUserToken>  toKenList = MyDeviceList.GetConnList();
                    AsyncUserToken[] toKenList = MyDeviceList.GetConnListToArray();
                    if (toKenList.Length > 0)
                    {
                        foreach (AsyncUserToken appToKen in toKenList)
                        {
                            OnOutputLog(LogInfoType.INFO, string.Format("发送消息({0})给APP[{1}:{2}]!",
                                                                        deviceServerMsgStruct.Body.type, appToKen.IPAddress, appToKen.Port), LogCategory.S);
                            OnOutputLog(LogInfoType.DEBG, string.Format("消息内容:\n{0}", strJosn), LogCategory.S);
                            MySocket.SendMessage(appToKen, buff);
                        }
                    }
                }
                else
                {
                    AsyncUserToken appToKen = MyDeviceList.FindByIpPort(appInfo.Ip, appInfo.Port);
                    if (appToKen == null)
                    {
                        OnOutputLog(LogInfoType.WARN, string.Format("设备列表中未找到该App设备[{0}:{1}]信息!", appInfo.Ip, appInfo.Port));
                        return;
                    }

                    OnOutputLog(LogInfoType.INFO, string.Format("发送消息({0})给APP[{1}:{2}]!",
                                                                deviceServerMsgStruct.Body.type, appToKen.IPAddress, appToKen.Port), LogCategory.S);
                    OnOutputLog(LogInfoType.DEBG, string.Format("消息内容:\n{0}", strJosn), LogCategory.S);
                    MySocket.SendMessage(appToKen, buff);
                }

                buff    = null;
                strJosn = null;
            }
            catch (Exception ee)
            {
                OnOutputLog(LogInfoType.EROR, "发送消息到App出错。出错原因:" + ee.Message, LogCategory.I);
            }

            return;
        }
コード例 #8
0
ファイル: Net_to_Serial.cs プロジェクト: mpostol/PO.Common
        private void ReenterReciveCallBack(MySocket m_s)
        {
            EndPoint endPoint = m_RemoteEndPoint;

            m_s.BeginReceiveFrom
                (m_Buffer, 0, c_buffCapacity, SocketFlags.None, ref endPoint, new AsyncCallback(ReciveCallBack), m_s);
            return;
        }
コード例 #9
0
    public void Ex33()
    {
        Dictionary <string, string> dict = new Dictionary <string, string> ();
        string aa = "{\"someKey\":\"someValue\", \"another\":\"value alasdlkfjasdf \"}";

        dict ["a"] = "[" + aa + "," + aa + "," + aa + "]";
        dict ["b"] = "[" + aa + "," + aa + "," + aa + "]";
        MySocket.Emit("GAMEMSG", dict);
    }
コード例 #10
0
        public string Send(string msg)
        {
            byte[] msgBuffer = Encoding.Default.GetBytes(msg);
            MySocket.Send(msgBuffer, 0, msgBuffer.Length, 0);

            var msgResponse = ReadResponse();

            return(msgResponse);
        }
コード例 #11
0
        public string ReadResponse()
        {
            byte[] buffer = new byte[255];
            int    rec    = MySocket.Receive(buffer, 0, buffer.Length, 0);

            Array.Resize(ref buffer, rec);

            return(Encoding.Default.GetString(buffer));
        }
コード例 #12
0
 protected virtual void SocketMessageHandler(MySocket sender, Utility.Messages.NuovaSchedaRifiutataMessageEventArgs e)
 {
     foreach (Utility.IComponent c in _components)
     {
         if (c is GestoreSchedeGiocatore)
         {
             c.Input(e);
         }
     }
 }
コード例 #13
0
 protected virtual void SocketMessageHandler(MySocket sender, Utility.Messages.RichiestaModificaCampoSchedaMessageEventArgs e)
 {
     foreach (Utility.IComponent c in _components)
     {
         if (c is GestoreSchedeMaster)
         {
             c.Input(e);
         }
     }
 }
コード例 #14
0
 protected virtual void SocketMessageHandler(MySocket sender, Utility.Messages.RichiestaNuovaSchedaMessageEventArgs e)
 {
     foreach (Utility.IComponent c in _components)
     {
         if (c is GestoreSchedeMaster)
         {
             c.Input(new Utility.Messages.GestoreGiocatoriMessageEventArgs(sender.RemoteAddress, e));
         }
     }
 }
コード例 #15
0
 protected virtual void SocketMessageHandler(MySocket sender, Utility.Messages.ChatCoordinamentoMessageEventArgs e)
 {
     foreach (IComponent c in _components)
     {
         if (c is ChatCoordinamentoGiocatore)
         {
             c.Input(e);
         }
     }
 }
コード例 #16
0
 protected override void SocketMessageHandler(MySocket sender, ChatComuneMessageEventArgs e)
 {
     foreach (Utility.IComponent c in _components)
     {
         if (c is ChatComune || c is MySocket)
         {
             c.Input(e);                                                                             //
         }
     }
 }
コード例 #17
0
ファイル: Net_to_Serial.cs プロジェクト: mpostol/PO.Common
        /// <summary>
        /// Ends a pending asynchronous read.
        /// </summary>
        /// <param name="ar">An IAsyncResult that stores state information for this asynchronous operation
        /// as well as any user defined data.
        /// </param>
        private void ReciveCallBack(IAsyncResult ar)
        {
            MySocket m_s = null;

            try
            {
                m_s = (MySocket)ar.AsyncState;
                EndPoint endPoint = m_RemoteEndPoint;
                int      lngt     = m_s.EndReceiveFrom(ar, ref endPoint);
                if (lngt > 0 && !EndPointsAreEqual(m_RemoteEndPoint, endPoint))
                {
                    TraceEvent(TraceEventType.Error, 207, "We have got frame from unepected address");
                    Debug.Fail("We have got frame from unepected address");
                    ReenterReciveCallBack(m_s);
                    return;
                }
                if (lngt == 0)
                {
                    // according to: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.endreceivefrom%28v=VS.80%29.aspx
                    // Return Value - If successful, the number of bytes received. If unsuccessful, returns 0.
                    // The EndReceiveFrom method will block until data is available. If you are using a connectionless protocol,
                    // EndReceiveFrom will read the first enqueued datagram available in the incoming network buffer.
                    // If you are using a connection-oriented protocol, the EndReceiveFrom method will read as much data as is available
                    // up to the number of bytes you specified in the size parameter of the BeginReceiveFrom method.
                    // If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received,
                    // the EndReceiveFrom method will complete immediately and return zero bytes.
                    TraceEvent(TraceEventType.Information, 226,
                               "The unexpected empty frame (0 length) was received. This would happen if the remote host shuts down the connection and all available data has been received previously.");
                    if (this.m_ProtocolType == ProtocolType.Udp)
                    {
                        //UDP:
                        ReenterReciveCallBack(m_s);
                    }
                    else
                    {
                        //TCP:
                        // We do not need to reenter callback (ReenterReciveCallBack( m_s );) because the connection might be closed
                        // We have to set that the buffer is empty:
                        m_Position   = int.MaxValue;
                        m_DataLength = 0;
                    }
                    return;
                }
                m_DataLength = lngt;
                m_Position   = 0;
            }
            catch (Exception ex)
            {
                m_s.LastException = ex;
            }
            finally
            {
                m_ReceiveNotStarted.Set();
            }
        }
コード例 #18
0
 public ControlCenter()
 {
     if (mySocket == null)
     {
         lock (_lock)
         {
             mySocket = MySocket.GetInstance();
             mySocket.coreProccessing += dataProccess;
         }
     }
 }
コード例 #19
0
 protected virtual void SocketMessageHandler(MySocket sender, Utility.Messages.GiocatoreCollegatoMessageEventArgs e)
 {
     foreach (Utility.IComponent c in _components)
     {
         if (c is GestoreSchedeMaster)
         {
             c.Input(new GestoreGiocatoriMessageEventArgs(sender.RemoteAddress, e));
         }
     }
     this.MessageForwarder(sender, new ChatComuneMessageEventArgs(e.NomeGiocatore + " partecipa ora alla partita \"" + DocumentoMaster.GetIstance().CurrentDescrittore.Nome + "\""));
 }
コード例 #20
0
    public void Ex3(int pNum)
    {
        Ag.LogStartWithStr(2, mName + "  Ex3    Emit  ...  \t\t\t\t <<<   Action :: GameMsg >>>");
        List <string> aList = new List <string> ();

        for (int k = 0; k < pNum; k++)
        {
            aList.Add(aa);
        }
        MySocket.Emit("GAMEMSG", aList);
    }
コード例 #21
0
 protected virtual void SocketMessageHandler(MySocket sender, Utility.Messages.SocketClosedMessageEventArgs e)
 {
     foreach (Utility.IComponent c in _components)
     {
         if (c is GestoreSchedeMaster)
         {
             c.Input(new GestoreGiocatoriMessageEventArgs(e.Argomento, e));
         }
     }
     sender.Dispose();
     _components.Remove(sender);
 }
コード例 #22
0
 protected override void SocketMessageHandler(MySocket sender, Utility.Messages.SocketErrorMessageEventArgs e)
 {
     sender.Dispose();
     _components.Remove(sender);
     foreach (IComponent c in _components)
     {
         if (c is ChatComune)
         {
             c.Input(new Utility.Messages.ChatComuneMessageEventArgs("Il Master ha chiuso la connessione"));
         }
     }
 }
コード例 #23
0
 private void Receive()
 {
     try
     {
         StateObject state = new StateObject();
         state.WorkSocket = MySocket;
         MySocket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
コード例 #24
0
    public void Ex1(int pNum)
    {
        Ag.LogStartWithStr(2, mName + "  Ex1    Emit  ...  \t\t\t\t <<<   Action :: GameMsg >>>");
        Dictionary <string, string> dict = new Dictionary <string, string> ();
        string aX = "";

        for (int k = 0; k < pNum; k++)
        {
            aX += aa;
        }
        dict ["a"] = aX;
        MySocket.Emit("GAMEMSG", dict);
    }
コード例 #25
0
ファイル: Hosts.cs プロジェクト: pkompalka/EON_emulator
        private void MyConnect(HostLogs window)
        {
            try
            {
                mySocket = new MySocket(CloudIPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                mySocket.Connect(new IPEndPoint(CloudIPAddress, CloudPort));
                mySocket.Send(Encoding.ASCII.GetBytes("HELLO " + HostName));

                Task.Run(() => { MyListen(window); });
            }
            catch (Exception)
            {
            }
        }
コード例 #26
0
ファイル: Net_to_Serial.cs プロジェクト: mpostol/PO.Common
 /// <summary>
 /// Disconnect Request - Unconditionally disconnect the connection if any.
 /// </summary>
 void IConnectionManagement.DisReq()
 {
     if (!IsConnected)
     {
         string cMsg = "DisReq: Client called disconnect request while it is not allowed in the state: : " + IsConnected.ToString();
         TraceEvent(TraceEventType.Error, 537, cMsg);
     }
     TraceEvent(TraceEventType.Verbose, 636, "DisReq: Start unconditionally disconnect the connection if any.");
     try
     {
         Debug.Assert(m_Socket != null, "To disconnect the socket it must not be null");
         if (m_Socket.ProtocolType == System.Net.Sockets.ProtocolType.Tcp)
         {
             m_Socket.Shutdown(SocketShutdown.Both);
             m_Socket.Disconnect(false);
             Debug.Assert(!m_Socket.Connected, "After disconnecting the socked must be disconnected to release the used endpoint");
         }
     }
     catch (SocketException ex)
     {
         MarkSocketException(ex, 514);
     }
     catch (ObjectDisposedException ex)
     {
         MarkSocketException(ex, 519);
     }
     catch (Exception ex)
     {
         MarkException(String.Format(m_ExceptionMesage, ex.Message), TraceEventType.Error, 304, ex);
     }
     finally
     {
         m_Socket.Close();
         m_ReceiveNotStarted.WaitOne(Timeout.Infinite);
         if (m_Socket.LastException != null)
         {
             if (m_Socket.LastException is ObjectDisposedException)
             {
                 TraceEvent(TraceEventType.Verbose, 516, "Finish of ReciveCallBack because of Disconnecting");
             }
             else
             {
                 TraceEvent(TraceEventType.Warning, 518, String.Format(m_ExceptionMesage, m_Socket.LastException.Message));
             }
         }
         m_Socket = null;
     }
 }
コード例 #27
0
ファイル: TcpSocket.cs プロジェクト: twinbird827/ConsoleApp1
        /// <summary>
        /// ソケット通信終了
        /// </summary>
        public void Close()
        {
            Console.WriteLine("{0} Close", DateTime.Now.ToString("HH:mm:ss.fff"));

            //Socketを停止
            MySocket.Shutdown(SocketShutdown.Both);
            MySocket.Disconnect(false);
            MySocket.Dispose();
            MySocket = null;

            //受信データ初期化
            InitializeStream();

            // 接続断イベント発生
            OnDisconnected(this, new EventArgs());
        }
コード例 #28
0
        protected virtual void SocketMessageHandler(MySocket sender, Utility.Messages.SocketErrorMessageEventArgs e)
        {
            String nome = "";

            foreach (Utility.IComponent c in _components)
            {
                if (c is GestoreSchedeMaster)
                {
                    nome = (c as GestoreSchedeMaster).getNomeGiocatore(e.Argomento);
                    c.Input(new GestoreGiocatoriMessageEventArgs(e.Argomento, e));
                }
            }
            sender.Dispose();
            _components.Remove(sender);
            this.MessageForwarder(sender, new ChatComuneMessageEventArgs(nome + " ha abbandonato la partita"));
        }
コード例 #29
0
ファイル: Net_to_Serial.cs プロジェクト: mpostol/PO.Common
        /// <summary>
        /// Ends a pending asynchronous connection request.
        /// </summary>
        /// <param name="ar">
        /// An IAsyncResult that stores state information for this asynchronous operation
        /// as well as any user defined data.
        /// </param>
        private void ConnectCallBack(IAsyncResult ar)
        {
            MySocket m_s = null;

            try
            {
                m_s = (MySocket)ar.AsyncState;
                m_s.EndConnect(ar);
            }
            catch (Exception ex)
            {
                m_s.LastException = ex;
                TraceEvent(TraceEventType.Verbose, 183, "An exception has been thrown by the ConnCallBack");
            }
            finally { m_ConnectWaitAsnychResponse.Set(); }
        }
コード例 #30
0
        private void ConnectToCloud()
        {
            Dispatcher.Invoke(new Action(() =>
            {
                NewLog("Trying to connect with Cable Cloud", this, "LightYellow");
            }));

            try
            {
                MySocket socket = new MySocket(networknode.CloudIP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                socket.Connect(new IPEndPoint(networknode.CloudIP, networknode.CloudPort));

                socket.Send(Encoding.ASCII.GetBytes($"HELLO {networknode.NodeName}"));
                Dispatcher.Invoke(new Action(() =>
                {
                    NewLog("Connected with Cable Cloud", this, "LightYellow");
                }));

                Task.Run(() => Listen());

                mySocket = socket;

                Task.Run(async() =>
                {
                    while (true)
                    {
                        var tmp = mySocket != null && mySocket.Connected;
                        if (tmp)
                        {
                            mySocket.Send(Encoding.ASCII.GetBytes("C"));

                            await Task.Delay(5000);
                        }
                        else
                        {
                            NewLog("Broken connection with cloud", this);
                            break;
                        }
                    }
                });
            }
            catch (Exception)
            {
                NewLog("No connection with Cloud", this);
            }
        }
コード例 #31
0
		public Worker(string szSvrAddr,int svrPort,MySocket pOwner)
		{
            m_pOwner = pOwner;
            m_enStatus = EnNetState.start_run;
			IPAddress tIpAddr = IPAddress.Parse(szSvrAddr);
			m_tSvrIp = new IPEndPoint(tIpAddr,svrPort);
            m_tSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_tSocket.Blocking = true;//
            try
            {
                Debug.Log("Begin Connect!");
                m_tSocket.BeginConnect(m_tSvrIp, new AsyncCallback(ConnectCallback), m_tSocket); 
            }
            catch (Exception se)
            {
                m_enStatus = EnNetState.connect_fail;
                Debug.Log("Connecting failed!");
                return;
            }

            m_enStatus = EnNetState.connecting;

            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
		}
コード例 #32
0
ファイル: Connection.cs プロジェクト: feamorx86/UnityChatTest
 public bool connect()
 {
     bool result = false;
     lock (this)
     {
         clear();
         try
         {
             connection = new MySocket();
             connection.Connect(serverAddress, serverPort);
             writer = new EndianBinaryWriter(EndianBitConverter.Big, connection.GetStream());
             reader = new EndianBinaryReader(EndianBitConverter.Big, connection.GetStream());
             result = true;
         }
         catch (Exception ex)
         {
             result = false;
             Debug.LogError("Fail to connect to remote server (" + serverAddress.ToString() + ":" + serverPort.ToString() + ") error :" + ex);
             fireErrorHandlers(ConnectionErrors.CONNECT, "Connect to server error.", ex);
         }
     }
     return result;
 }
コード例 #33
0
ファイル: Service1.cs プロジェクト: CarverLab/Oyster
 void ThreadMain()
 {
     log.WriteLog("Starting...");
     MySocket mysocket = new MySocket(MySocket.MySocketType.UdpSocket,MySocket.BUFFER_SIZE,22580);
     ContinueProcessing = new System.Threading.AutoResetEvent(false);
     while (!IsDone)
     {
         mysocket.socketLocal.BeginReceiveFrom(mysocket.buffer,0,MySocket.BUFFER_SIZE,SocketFlags.None,
             ref mysocket.epRemote,new AsyncCallback(this.Listener),mysocket);
         while (!IsDone)
         {
             if (ContinueProcessing.WaitOne(1000,false))
                 break;
         }
     }
 }
コード例 #34
0
ファイル: Connection.cs プロジェクト: feamorx86/UnityChatTest
    private void clear()
    {
        lock (messagesToSend)
        {
            messagesToSend.Clear();
        }

        lock (dataListeners)
        {
            dataListeners.Clear();
        }

        if (connection != null)
        {
            if (connection.Connected)
            {
                writer.Close();
                reader.Close();
            }
            connection.Close();
            connection = null;
        }
    }
コード例 #35
0
ファイル: COrb.cs プロジェクト: wangscript/zephyr-platform
 void Init(MySocket pSocket)
 {
     m_pSocket = pSocket;
 }