Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
0
 public static Encoding GetEncoder(string codePageName)
 {
     try
     {
         return(Encoding.GetEncoding(codePageName));
     }
     catch (Exception err)
     {
         SocketLogMgt.SetLastError(err);
         return(Encoding.UTF8);
     }
 }
Ejemplo n.º 5
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);
            }
        }
Ejemplo n.º 6
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();
        }
Ejemplo n.º 7
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");
        }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
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);
            }
        }
Ejemplo n.º 10
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);
            }
        }
Ejemplo n.º 11
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);
        }