예제 #1
0
        private void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                if (!_isListening)
                {
                    return;
                }
                Socket socket = _listener.EndAccept(asyn);
                if (socket == null)
                {
                    return;
                }

                int id = SocketHelper.GetNewSocketID();

                SocketLogMgt.SetLog(this, "=============================================");
                SocketLogMgt.SetLog(this, ": Client Connected.");
                SocketLogMgt.SetLog(this, ": Worker Socket Created. ID: " + id.ToString());

                //socket.NoDelay = true;
                SocketWorker worker = new SocketWorker(id, socket, this);
                worker.ReceiveData();

                _listener.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
            }
        }
예제 #2
0
        public bool Start()
        {
            bool result;

            SocketLogMgt.SetLog(this, "=============================================");
            SocketLogMgt.SetLog(this, ": Start Socket Listening.");

            try
            {
                if (_config.EnableConnectionCollecting)
                {
                    _timer.Start();
                }

                _listener.SendTimeout    = _config.SendTimeout;
                _listener.ReceiveTimeout = _config.ReceiveTimeout;
                _listener.Listen(_config.BackLog);
                _listener.BeginAccept(new AsyncCallback(OnClientConnect), null);

                _isListening = true;
                result       = true;
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
                _isListening = false;
                result       = false;
            }

            SocketLogMgt.SetLog(this, ": Start Socket Listening Result: " + result.ToString());
            SocketLogMgt.SetLog(this, "=============================================\r\n");
            return(result);
        }
예제 #3
0
        public bool Stop()
        {
            bool result;

            SocketLogMgt.SetLog(this, "=============================================");
            SocketLogMgt.SetLog(this, ": Stop Socket Listening.");

            try
            {
                if (_timer.Enabled)
                {
                    _timer.Stop();
                }

                _isListening = false;
                _listener.Close();
                result = true;
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
                result = false;
            }

            SocketLogMgt.SetLog(this, ": Stop Socket Listening Result: " + result.ToString());
            SocketLogMgt.SetLog(this, "=============================================\r\n");
            return(result);
        }
예제 #4
0
        private void ResponseData(string sendData)
        {
            string strSend = SocketHelper.EnsureEOF(sendData, _entity.Config.SendEndSign);

            if (SocketLogMgt.DumpData)
            {
                SocketLogMgt.SetLog(this, _logID + ": Data to be sent.");
                SocketLogMgt.SetLog(this, "------------------------");
                SocketLogMgt.SetLog(this, strSend);
                SocketLogMgt.SetLog(this, "------------------------");
            }

            byte[] byteData = null;
            if (_entity.Config.IncludeHeader)
            {
                byteData = SocketHelper.GetResponseByteWithHeader(_entity.Encoder, strSend, _entity.Config);
            }
            else
            {
                byteData = _entity.Encoder.GetBytes(strSend);
            }

            if (byteData == null)
            {
                SocketLogMgt.SetLog(SocketLogType.Error, "Encode data failed.");
            }
            else
            {
                _socket.BeginSend(byteData, 0, byteData.Length, 0,
                                  new AsyncCallback(OnDataSent), null);
            }
        }
예제 #5
0
        public void ReceiveData()
        {
            _entity.AddWorker(this);
            SocketLogMgt.SetLog(this, _logID + "Begin receive data.");

            _socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.Peek,
                                 new AsyncCallback(OnDataReceived), null);
        }
예제 #6
0
        private void DisplayWorker()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Worker List: ");
            foreach (SocketWorker sw in Workers)
            {
                sb.Append(sw.LogID);
            }
            SocketLogMgt.SetLog(sb.ToString());
        }
예제 #7
0
 public static Encoding GetEncoder(string codePageName)
 {
     try
     {
         return(Encoding.GetEncoding(codePageName));
     }
     catch (Exception err)
     {
         SocketLogMgt.SetLastError(err);
         return(Encoding.UTF8);
     }
 }
예제 #8
0
        private void OnDataReceived(IAsyncResult asyn)
        {
            int bytesRead = _socket.EndReceive(asyn);

            //------------Handle Multi-byte Charactor-------------
            _bufferList = new List <BufferWrapper>();
            //----------------------------------------------------

            do
            {
                bytesRead = _socket.Receive(_buffer);
                SocketLogMgt.SetLog(this, _logID + "Receive succeeded. " + bytesRead.ToString() + " bytes.");

                //------------Handle Multi-byte Charactor-------------
                _bufferList.Add(BufferWrapper.Create(_buffer, bytesRead));
                //foreach (BufferWrapper w in _bufferList) SocketLogMgt.SetLog(">>>>>>>>>>>> " + w.Buffer.Length.ToString());
                //----------------------------------------------------

                if (bytesRead > 0)
                {
                    //No matter how to cut the buffer, ASCII charactor can always be decoded properly,
                    //therefore we can use this segment to detect whether an ending sign (for example "</XMLRequestMessage>") is received.
                    //See class XmlTest.FormCoding for unit test.
                    string str = _entity.Encoder.GetString(_buffer, 0, bytesRead);
                    _sb.Append(str);

                    if (SocketLogMgt.DumpData)
                    {
                        SocketLogMgt.SetLog(this, _logID + ": Data received.");
                        SocketLogMgt.SetLog(this, "------------------------");
                        SocketLogMgt.SetLog(this, str);
                        SocketLogMgt.SetLog(this, "------------------------");
                    }

                    string receiveData = _sb.ToString();
                    if (SocketHelper.IsEOF(receiveData, _entity.Config.ReceiveEndSign))
                    {
                        string sendData = null;

                        //------------Handle Multi-byte Charactor-------------
                        receiveData = BufferWrapper.GetString(_entity.Encoder, _bufferList);
                        _bufferList = null;
                        //----------------------------------------------------

                        _entity.NotifyRequest(receiveData, ref sendData);
                        ResponseData(sendData);
                        break;
                    }
                }
            }while (bytesRead > 0);
        }
예제 #9
0
        public static SocketEntity Create(int port)
        {
            try
            {
                SocketConfig cfg = new SocketConfig();
                cfg.Port = port;

                Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(new IPEndPoint(IPAddress.Any, port));
                return(new SocketEntity(listener, cfg));
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
                return(null);
            }
        }
예제 #10
0
        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Stop();

            DisplayWorker();

            DateTime            dt     = DateTime.Now;
            List <SocketWorker> gcList = new List <SocketWorker>();

            foreach (SocketWorker sw in Workers)
            {
                //if (sw._socket.Connected) continue;
                TimeSpan ts = dt.Subtract(sw.CreateDT);
                if (ts.Seconds >= _config.ConnectionTimeoutSecond)
                {
                    gcList.Add(sw);
                }
            }

            foreach (SocketWorker sw in gcList)
            {
                try
                {
                    SocketLogMgt.SetLog(SocketLogType.Warning, "Collect Garbage Connection: (" + sw.LogID + ") ");
                    sw._socket.Shutdown(SocketShutdown.Both);
                    sw._socket.Close();
                }
                catch (Exception err)
                {
                    SocketLogMgt.SetLastError(err);
                }
                finally
                {
                    //put it into .Net GC
                    Workers.Remove(sw);
                }
            }

            DisplayWorker();

            _timer.Start();
        }
예제 #11
0
        private void OnDataSent(IAsyncResult asyn)
        {
            try
            {
                int bytesSent = _socket.EndSend(asyn);
                SocketLogMgt.SetLog(this, _logID + "Sent succeeded. " + bytesSent.ToString() + " bytes.");

                _socket.Shutdown(SocketShutdown.Both);
                _socket.Close();

                _entity.RemoveWorker(this);
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
            }

            SocketLogMgt.SetLog(this, ": Client Disconnected.");
            SocketLogMgt.SetLog(this, "=============================================\r\n");
        }
예제 #12
0
        private static void OnDataSent(IAsyncResult asyn)
        {
            try
            {
                SocketWrapper s = asyn.AsyncState as SocketWrapper;
                if (s == null)
                {
                    return;
                }

                int bytesSent = s.Socket.EndSend(asyn);
                SocketLogMgt.SetLog(s.ID + "Sent succeeded. " + bytesSent.ToString() + " bytes.");

                _allDone.Set();
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
            }
        }
예제 #13
0
        public static SocketEntity Create(string ip, int port)
        {
            if (ip == null || ip.Length < 1 || ip == "127.0.0.1")
            {
                return(Create(port));
            }
            try
            {
                SocketConfig cfg = new SocketConfig();
                cfg.IPAddress = ip;
                cfg.Port      = port;

                Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
                return(new SocketEntity(listener, cfg));
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
                return(null);
            }
        }
예제 #14
0
        public static SocketEntity Create(SocketConfig config)
        {
            try
            {
                int    port = config.Port;
                string ip   = config.IPAddress;

                Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (ip == null || ip.Length < 1 || ip == "127.0.0.1")
                {
                    listener.Bind(new IPEndPoint(IPAddress.Any, port));
                }
                else
                {
                    listener.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
                }
                return(new SocketEntity(listener, config));
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
                return(null);
            }
        }
예제 #15
0
        public static SocketResult SendData(SocketConfig config, string content)
        {
            SocketResult result = SocketResult.Empty;

            try
            {
                SocketLogMgt.SetLog("=============================================");
                SocketLogMgt.SetLog(": Send Data Begin.");
                SocketLogMgt.SetLog(config);

                string strSend = EnsureEOF(content, config.SendEndSign);

                if (SocketLogMgt.DumpData)
                {
                    SocketLogMgt.SetLog(": Data to be sent.");
                    SocketLogMgt.SetLog("------------------------");
                    SocketLogMgt.SetLog(strSend);
                    SocketLogMgt.SetLog("------------------------");
                }

                Byte[]   bytesSent = null;
                Encoding encoder   = GetEncoder(config.CodePageName);
                if (config.IncludeHeader)
                {
                    bytesSent = GetRequestByteWithHeader(encoder, strSend, config);
                }
                else
                {
                    bytesSent = encoder.GetBytes(strSend);
                }
                if (bytesSent == null)
                {
                    SocketLogMgt.SetLog(SocketLogType.Error, "Encode data failed.");
                    return(SocketResult.SendFailed);
                }

                Byte[] bytesReceived = new Byte[ReceiveResponseBufferSize];

                SocketLogMgt.SetLog(": Socket prepared.");
                SocketLogMgt.SetLog("------------------------");

                string        strReceived = null;
                StringBuilder sb          = new StringBuilder();
                IPEndPoint    ipe         = new IPEndPoint(IPAddress.Parse(config.IPAddress), config.Port);
                using (Socket socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                {
                    int    id    = GetNewSocketID();
                    string strID = "(" + id.ToString() + ") ";

                    //socket.NoDelay = true;
                    socket.SendTimeout    = config.SendTimeout;
                    socket.ReceiveTimeout = config.ReceiveTimeout;

                    SocketLogMgt.SetLog(strID + "Socket created.");

                    socket.Connect(ipe);
                    if (socket.Connected)
                    {
                        SocketLogMgt.SetLog(strID + "Socket connected.");
                    }
                    else
                    {
                        SocketLogMgt.SetLog(SocketLogType.Warning, strID + "Connection failed.");
                        return(SocketResult.Disconnect);
                    }

                    _allDone.Reset();
                    SocketLogMgt.SetLog(strID + "Send data.");
                    socket.BeginSend(bytesSent, 0, bytesSent.Length, 0,
                                     new AsyncCallback(OnDataSent), new SocketWrapper(strID, socket));

                    bool rec = true;
                    while (rec)
                    {
                        if (!socket.Connected)
                        {
                            SocketLogMgt.SetLog(SocketLogType.Warning, strID + "Connection closed.");
                            break;
                        }

                        SocketLogMgt.SetLog(strID + "Receive data.");
                        int bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
                        SocketLogMgt.SetLog(strID + "Receive succeeded. " + bytes.ToString() + " bytes.");
                        string str = encoder.GetString(bytesReceived, 0, bytes);
                        sb.Append(str);

                        strReceived = sb.ToString();
                        rec         = !IsEOF(strReceived, config.ReceiveEndSign);
                    }

                    _allDone.WaitOne();

                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();

                    SocketLogMgt.SetLog(strID + "Socket disconnected.");
                }

                SocketLogMgt.SetLog("------------------------");

                if (SocketLogMgt.DumpData)
                {
                    SocketLogMgt.SetLog(": Data received.");
                    SocketLogMgt.SetLog("------------------------");
                    SocketLogMgt.SetLog(strReceived);
                    SocketLogMgt.SetLog("------------------------");
                }

                strReceived = GetMessageContent(strReceived);
                result      = new SocketResult(strReceived);
            }
            catch (Exception err)
            {
                SocketLogMgt.SetLastError(err);
                result = new SocketResult(err);
            }

            SocketLogMgt.SetLog(": Send Data End");
            SocketLogMgt.SetLog("=============================================\r\n");
            return(result);
        }