Exemplo n.º 1
0
        public static void Main(string[] args)
        {
            AsyncSocketServerReceive.LittleEndian   = true;
            AsyncSocketServerReceive.MaxPackageSize = 1024 * 1024;
            AsyncSocketServerReceive.ErrorMsg       = ServerMsg;
            AsyncSocketServerReceive.RegisterEvent <LoginEvent>(Command.Login);
            AsyncSocketServerReceive.RegisterEvent <FriendsEvent>(Command.Friends);
            AsyncSocketServerReceive.RegisterEvent <LabaEvent>(Command.BigData);

            server               = new AsyncSocketServer("tcp://*:3000", 100, 4096);
            server.Connected    += new EventHandler <AsyncSocketTokenEventArgs>(server_Connected);    //连接成功
            server.Disconnected += new EventHandler <AsyncSocketTokenEventArgs>(server_Disconnected); //断开连接
            server.DataReceived += new EventHandler <AsyncSocketTokenEventArgs>(server_DataReceived); //接收到数据
            server.Error        += new EventHandler <AsyncSocketErrorEventArgs>(server_Error);        //出错
            server.Start();                                                                           //开始监听
            ServerMsg("监听端口3000");

            Thread.Sleep(10000000);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            DateTime currentTime = DateTime.Now;

            log4net.GlobalContext.Properties["LogDir"]      = currentTime.ToString("yyyyMM");
            log4net.GlobalContext.Properties["LogFileName"] = "_SocketAsyncServer" + currentTime.ToString("yyyyMMdd");
            Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            //todo:性能测试
            int port = 0;

            port = 8103;
            int parallelNum = 100;

            parallelNum = 100;//并发数量
            int socketTimeOutMS = 0;

            socketTimeOutMS = 5 * 60 * 1000;

            Logger.Debug("for test");
            Logger.Info("for test info");
            Logger.Error("for test error");

            dm = new DataManager();

            AsyncSocketSvr = new AsyncSocketServer(parallelNum);
            AsyncSocketSvr.SocketTimeOutMS = socketTimeOutMS;
            AsyncSocketSvr.Init();
            IPEndPoint listenPoint = new IPEndPoint(GetIPAddress(), port);

            AsyncSocketSvr.Start(listenPoint);

            Console.WriteLine("Press any key to terminate the server process....");


            //for ring buffer test--begin--OK
            ///正式环境中,把SMELLsocketTest.cs/RingBufferManager.cs删除
            //    SMELLsocketTest sst = new SMELLsocketTest();
            //for ring buffer test--end--OK

            Console.ReadKey();
        }
Exemplo n.º 3
0
    /// <inheritdoc />
    public override void StartHostingService()
    {
        if (IsHostingServiceRunning)
        {
            return;
        }

        if (HostingServicePort <= 0)
        {
            HostingServicePort = GetAvailablePort();
        }
        else if (!IsPortAvailable(HostingServicePort))
        {
            LogError("Port {0} is in use, cannot start service!", HostingServicePort);
            return;
        }

        if (HostingServiceContentRoots.Count == 0)
        {
            throw new Exception(
                      "ContentRoot is not configured; cannot start service. This can usually be fixed by modifying the BuildPath for any new groups and/or building content.");
        }

        ConfigureHttpListener();
        MyHttpListener.Start();
        MyHttpListener.BeginGetContext(HandleRequest, null);
        Log("Started. Listening on port {0}", HostingServicePort);

        //
        if (socketListener == null)
        {
            socketListener = new AsyncSocketServer();
        }
        var socketLocalEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), HotfixManager.Instance.ipPort);

        socketListener.Start(socketLocalEndPoint);
    }
Exemplo n.º 4
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (!ss.IsListening)
            {
                ss                = new AsyncSocketServer(new IPEndPoint(IPAddress.Any, Convert.ToInt32(this.numericUpDown1.Value)), Convert.ToInt32(this.numericUpDown2.Value), Convert.ToInt32(this.numericUpDown3.Value));
                ss.Connected     += new EventHandler <AsyncSocketUserTokenEventArgs>(ss_Connected);
                ss.DataReceived  += new EventHandler <AsyncSocketUserTokenEventArgs>(ss_DataReceived);
                ss.DataSent      += new EventHandler <AsyncSocketUserTokenEventArgs>(ss_DataSent);
                ss.Disconnected  += new EventHandler <AsyncSocketUserTokenEventArgs>(ss_Disconnected);
                ss.ErrorOccurred += new EventHandler <AsyncSocketErrorEventArgs>(ss_ErrorOccurred);

                try
                {
                    ss.Start();

                    this.Invoke((MethodInvoker) delegate
                    {
                        richTextBox1.AppendText(string.Format("-> Server start to listening port: {0}", ss.LocalEndPoint.Port));
                        richTextBox1.AppendText(Environment.NewLine);
                        richTextBox1.ScrollToCaret();
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                this.Invoke((MethodInvoker) delegate
                {
                    richTextBox1.AppendText(string.Format("-> Server is listening port: {0}", ss.LocalEndPoint.Port));
                    richTextBox1.AppendText(Environment.NewLine);
                    richTextBox1.ScrollToCaret();
                });
            }
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("=====================");
            Console.WriteLine("SignPressServer BUILD-2016-06-1");
            Console.WriteLine("=====================");

            Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory);

            Console.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            //Console.WriteLine(System.DateTime.Now.ToString("yyyyMMddHHmmss"));
            //string contractId = "佳内2015001";
            //Console.Write(DALHDJContract.GetDepartmentShortCallFromContractId(contractId));
            //Console.Write(DALHDJContract.GetCatgoryShortCallFromContractId(contractId));
            //Console.Write(DALHDJContract.GetYearFromContractId(contractId));
            //Console.Write(DALHDJContract.GetIsOnlineFromContractId(contractId));
            //Console.Write(DALHDJContract.GetNumFromContractId(contractId));

            //获取当前进程的完整路径,包含文件名(进程名)。
            //Console.WriteLine(this.GetType().Assembly.Location);
            //result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名)

            //获取新的Process 组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名(进程名)。
            //Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            //result: X:\xxx\xxx\xxx.exe (.exe文件所在的目录+.exe文件名)

            //获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。
            //Console.WriteLine(System.Environment.CurrentDirectory);
            //result: X:\xxx\xxx (.exe文件所在的目录)

            //获取当前 Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集。
            //Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory);
            //result: X:\xxx\xxx\ (.exe文件所在的目录+"\")

            //获取和设置包含该应用程序的目录的名称。
            //Console.WriteLine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
            //result: X:\xxx\xxx\ (.exe文件所在的目录+"\")

            //获取应用程序的当前工作目录(不可靠)。
            //Console.WriteLine(System.IO.Directory.GetCurrentDirectory());
            //result: X:\xxx\xxx (.exe文件所在的目录)
            /// 测试连接服务器以及查询测试


            //int currDayConCount = DALHDJContract.GetDayHDJContractCount(System.DateTime.Now.Date);
            //Console.WriteLine(System.DateTime.Now.ToString("yyyyMMdd") + (currDayConCount + 1).ToString().PadLeft(6, '0'));


            #region 测试正则表达式
//            String[] text = {   "username/password@//myserver:1521/my.service.com",
//                                "username/password@myserver//instancename",
//                                "username/password@myserver/myservice:dedicated/instancename"};
//            //Regex regex = new Regex(@"\S*/\S*@/*(\S*):(\S*)/(\S*)", RegexOptions.None);     // text1
//            //Regex regex = new Regex(@"\S*/\S*@/*(\S*):(\d*|/)/(\S*)", RegexOptions.None);     // text1
//            //Regex regex = new Regex(@"\S*/\S*@/*(\S*):(\d*|/*)/(\S*)", RegexOptions.None);     // text1

//            // 在第二个串中@后的`/`可省, myserver:1521中的:port也可以缺省,
//            //Regex regex = new Regex(@"\S*/\S*@/*(\S*)[:*(\S*) | (/*)]/{1,2}(\S*)", RegexOptions.None);     // text1 + text2
//            //Regex regex = new Regex(@"\S*/\S*@/*(\w*)(:*)(\d*)/*(\S*)", RegexOptions.None);     // text1 + text2

//            // 在第三个串中,
////            Regex regex = new Regex(@"\S*/\S*(@/{0,2})(\w*)(:*)(\d*)/*(\S*)(:*)(\S*)/(\S*)", RegexOptions.None);     // text1 + text2
//            Regex regex = new Regex(@"\S*/\S*(@/{0,2})(\w*):*(\d*)/*\S*:*\S*/(\S*)", RegexOptions.None);     // text1 + text2

//            //Console.WriteLine(text1);
//            for(int i = 0; i < 3; i++)
//            {
//                MatchCollection matchCollection = regex.Matches(text[i]);
//                Console.WriteLine("Count = " + matchCollection.Count);
//                for (int j = 0; j < matchCollection.Count; j++)
//                {
//                    Match match = matchCollection[j];
//                    Console.WriteLine("Match[{0}]========================", j);
//                    for (int k = 0; k < match.Groups.Count; k++)
//                    {
//                        Console.WriteLine("Groups[{0}]={1}", k, match.Groups[k].Value);
//                    }
//                }
//            }
            #endregion



            #region 测试数据库连接

            //  测试查询工作量信息集合item
            //List<ContractItem> items = DALContractItem.QueryProjectItem(1);
            //foreach (ContractItem item in items)
            //{
            //    Console.WriteLine(item.Id + ", " + item.ProjectId + ", " + item.Item);
            //}

            #endregion


            #region Word操作
            //Start Word and create a new document.

            /*
             * 首先添加COM组件Office,
             * 然后添加.Net组件引用Microsoft.Office.Interop.Word;
             * 接着添加如下的代码
             * using Office;
             * using Microsoft.Office.Interop.Word;
             * using Word = Microsoft.Office.Interop.Word;
             */
            /// 对word的操作信息
            //  将一个创建的WORD保存为PDF
            //MSWordTools.WordConvertToPdf(@"G:\[B]CodeRuntimeLibrary\[E]GitHub\\测试文档.doc",
            //    @"G:\[B]CodeRuntimeLibrary\[E]GitHub\测试文档.pdf");              将一个创建的WORD保存为PDF

            //String filePath = MSWordTools.DEFAULT_HDJCONTRACT_PATH + "20150712000005.pdf";
            //if (!(File.Exists((String)filePath)))     // 首先检测文件是否存在
            //{
            //    MSWordTools.KillWordProcess();
            //    String wordPath = MSWordTools.DEFAULT_HDJCONTRACT_PATH + "20150712000005.doc";
            //    HDJContract contract = DALHDJContract.GetHDJContactAgree("20150712000005");       // 获取待生成的会签单信息
            //    MSWordTools.CreateHDJContractWordWithReplace(contract, wordPath);
            //    MSWordTools.WordConvertToPdf(wordPath, filePath);

            //    File.Delete((String)wordPath);
            //    MSWordTools.KillWordProcess();
            //}
            //else
            //{
            //    Console.WriteLine("文件存在无需在生成");
            //}
            //MSWordTools.WordConvertToPdf();
            //MSExcelTools.Test();


            #endregion


            #region 测试JSON数据
            //Action<object> log = o => Console.WriteLine(o);


            //            var e1 = new Employee
            //            {
            //                Id = 1,
            //                Name = "成坚",
            //                Position = "科长",
            //                Department = new Department { Id = 1, Name = "申请科" },
            //                CanSubmit = true,
            //                CanSign = true,
            //                IsAdmin = true,
            //                User = new User { Username = "******", Password = "******" },

            //            };
            //            var e2 = new Employee
            //            {
            //                Id = 1,
            //                Name = "吴佳怡",
            //                Position = "局长",
            //                Department = new Department { Id = 5, Name = "行政科" },
            //                CanSubmit = true,
            //                CanSign = true,
            //                IsAdmin = true,
            //                User = new User{ Username = "******", Password = "******"},
            //            };
            //            e1.Show();
            //            e2.Show();
            //            //序列化 参数是要序列化的对象;json是对象序列化后的字符串
            //            String json = JsonConvert.SerializeObject(new Employee[] { e1, e2 });
            //            Console.WriteLine(json);
            //            //Employee是目标类型;json是经过Json序列化的对象,字符串形式
            //            List<Employee> employList = JsonConvert.DeserializeObject<List<Employee>>(json);
            //            JArray ja = JArray.Parse(json);
            //            Console.WriteLine(ja);	//注意,格式化过的输出
            //            foreach (Employee employ in employList)
            //            {
            //                employ.Show();
            //            }


            #endregion


            #region 测试统计的功能
            //MSExcelTools.KillExcelProcess();



            //MSExcelTools.CreateRegularloadTemplateFile(1);
            //MSExcelTools.CreateRegularloadTemplateFile(2);
            //MSExcelTools.CreateRegularloadTemplateFile(3);
            //MSExcelTools.CreateRegularloadTemplateFile(4);

            //MSExcelTools.UploadRegularLoad(2016, 2);
            //DALContractRegularoload.DeleteYearCategoryRegularload(2016, 2);
            //MSExcelTools.KillExcelProcess();
            #endregion


            #region 获取本机的IP
            //QUERY_UNSIGN_CONTRACT_REQUEST; 1; 1QUERY_SIGN_REFUSE_REQUEST; 1; 1
            //QUERY_REQUEST;0; QUERY_SIGN_REFUSE_REQUEST; 1; 1
            //QUERY_SIGN_REFUSE_REQUEST;1; 1; QUERY_REQUEST;0
            //QUERY_REQUEST;0; QUERY_REQUEST;0

            ////string s1 = "QUERY_REQUEST; QUERY_SIGN_REFUSE_REQUEST;1;1;";
//            AsyncSocketMessage message = new AsyncSocketMessage(ClientRequest.LOGIN_REQUEST);
//            message.Package = @"QUERY_UNSIGN_CONTRACT_RE
//            QUEST11QUERY_SIGN_REFUSE_REQU
//            EST1QUERY_SIGN_REFUSE_REQUES1";
//            // 3 5 7 9 11
//            do
//            {
//                if (message.Split() == AsyncSocketMessageFlag.MESSAGE_UNKOWN)   // 将数据包分割
//                {
//                    break;
//                }
//            }while(message.Flag != AsyncSocketMessageFlag.MESSAGE_RIGHT);

            string hostName = System.Net.Dns.GetHostName();                                 //本机名
            System.Net.IPAddress[] addressList = System.Net.Dns.GetHostAddresses(hostName); //会返回所有地址,包括IPv4和IPv6
            Console.WriteLine("HOST Name = " + hostName);
            foreach (System.Net.IPAddress ip in addressList)
            {
                Console.WriteLine("IP Address = " + ip.ToString());
            }
            #endregion


            //for (int row = 6, cnt = 0; row <= 8; row++)    // 填写表格的签字人表头
            //{

            //    for (int col = 1; col <= 3; col += 2, cnt++)
            //    {

            //        Console.WriteLine("签字人信息位置{0}, {1} ==== 签字人序号{2} ==== 签字位置{3},{4}", row, col, cnt, row, col + 1);

            //    }
            //}



            #region  务器的处理程序AsyncSocketServer

            Console.WriteLine("服务器准备中...");
            const int PORT = 6666;
            //System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("10.0.209.144"), 6666);
            AsyncSocketServer server = new AsyncSocketServer(PORT);
            while (true)
            {
                server.Start();
            }
            //SocketTCPServer server = new SocketTCPServer(6666);
            //server.Start();


            #endregion
        }