{"id":492,"date":"2017-05-01T16:44:58","date_gmt":"2017-05-01T07:44:58","guid":{"rendered":"http:\/\/masahiroshiomi.jp\/blog\/?p=492"},"modified":"2020-04-22T16:13:08","modified_gmt":"2020-04-22T07:13:08","slug":"c%e3%81%a7%e9%9d%9e%e5%90%8c%e6%9c%9f%e3%81%ae%e3%82%bd%e3%82%b1%e3%83%83%e3%83%88%e9%80%9a%e4%bf%a1","status":"publish","type":"post","link":"https:\/\/masahiroshiomi.jp\/blog\/c\/492\/","title":{"rendered":"C#\u3067\u975e\u540c\u671f\u306e\u30bd\u30b1\u30c3\u30c8\u901a\u4fe1"},"content":{"rendered":"\n<p>\u3053\u308c\u307e\u3067\u5927\u4f53\u30bd\u30b1\u30c3\u30c8\u901a\u4fe1\u306f\u540c\u671f\u51e6\u7406\u3067\u3084\u3063\u3066\u305f\u3093\u3060\u3051\u3069\u3001\u975e\u540c\u671f\u3067\u306e\u30bd\u30b1\u30c3\u30c8\u901a\u4fe1\u304c\u3057\u305f\u304f\u306a\u3063\u305f\u306e\u3067\u307e\u3068\u3081\u3066\u307f\u305f\u3002\u3068\u306f\u3044\u3048\u3001\u524d\u56de\u306eTouchence\u306e\u30b5\u30f3\u30d7\u30eb\u3067\u4f7f\u3063\u3066\u3044\u308b\u90e8\u5206\u3092\u5207\u308a\u51fa\u3057\u305f\u611f\u3058\u3002<\/p>\n\n\n\n<!--more-->\n\n\n<div class=\"my-ad-space\">\n<div class=\"my-ad-label\">\u30b9\u30dd\u30f3\u30b5\u30fc\u30ea\u30f3\u30af<\/div>\n<div>\n\n<script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script>\n<!-- \u30ec\u30b9\u30dd\u30f3\u30b7\u30d6 -->\n<ins class=\"adsbygoogle\"\n     style=\"display:block\"\n     data-ad-client=\"ca-pub-1956541408145992\"\n     data-ad-slot=\"6517671867\"\n     data-ad-format=\"auto\"><\/ins>\n<script>\n(adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n\n<\/div>\n<\/div>\n<br>\n\n\n\n<p>\u30bd\u30fc\u30b9\u30b3\u30fc\u30c9\u306f<a href=\"https:\/\/github.com\/MasahiroShiomi\/AsynchronousServerSample\">GitHub<\/a>\u306b\u4e0a\u3052\u3066\u308b\u3051\u3069\u3001\u30e1\u30a4\u30f3\u306e\u30bd\u30fc\u30b9\u3082\u30b3\u30d4\u30da\u3057\u3066\u307f\u305f\u3002\u30b5\u30fc\u30d0\u958b\u59cb\u6642\u306fStartListening\u3057\u3066\u3001\u7d42\u4e86\u6642\u306fStopListening\u3057\u3066\u308b\u3002ReadCallback\u3067Start\/Stop\u306e\u30b3\u30de\u30f3\u30c9\u304c\u6765\u305f\u3089\u6587\u5b57\u5217\u9001\u4fe1\u3092\u958b\u59cb\u3059\u308b\u30d5\u30e9\u30b0\u3092\u7acb\u3066\u3066\u3001SendMessageThread\u306e\u4e2d\u3067\u63a5\u7d9a\u3054\u3068\u306b\u30d5\u30e9\u30b0\u3092\u30c1\u30a7\u30c3\u30af\u3057\u3066\u6587\u5b57\u5217\u9001\u4fe1\u3092\u3057\u3066\u308b\u3002<\/p>\n\n\n\n<p>\u63a5\u7d9a\u3057\u3066\u304d\u305f\u30af\u30e9\u30a4\u30a2\u30f3\u30c8\u306b\u30c7\u30fc\u30bf\u3092\u5782\u308c\u6d41\u3057\u306a\u304c\u3089\u3001\u4f55\u304b\u30b3\u30de\u30f3\u30c9\u3092\u53d7\u3051\u53d6\u3063\u305f\u3089\u305d\u306e\u30c7\u30fc\u30bf\u306e\u5f62\u5f0f\u3092\u5909\u3048\u305f\u308a\u9001\u53d7\u4fe1\u305d\u306e\u3082\u306e\u3092\u6b62\u3081\u305f\u308a\u3059\u308b\u3063\u3066\u8a00\u3046\u306e\u304c\u51fa\u6765\u308b\u3068\u601d\u3046\u3093\u3060\u3051\u3069\u3001\u4ed6\u306e\u4eba\u305f\u3061\u306f\u3069\u3046\u3084\u3063\u3066\u308b\u306e\u304b\u306a\u3002\u9001\u4fe1\u3092\u5225\u30b9\u30ec\u30c3\u30c9\uff08SendMessageThread\uff09\u3067\u56de\u3057\u3066\u3044\u308b\u306e\u306f\u3001\u3061\u3087\u3063\u3068\u3060\u3051\u6c17\u6301\u3061\u60aa\u3044\u3093\u3060\u3051\u3069\u30fb\u30fb\u30fb<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    public partial class MainWindow : Window\n    {\n        public bool runSendDataThread { get; set; }\n        private Thread sendTouchDataThread { get; set; }\n        private int serverPort { get; set; }\n        private List activeConnections { get; set; }\n        private object lockObjectConnection { get; set; }\n        private Socket listener { get; set;}\n            \n\n        public MainWindow()\n        {\n            InitializeComponent();\n            lockObjectConnection = new object();\n            activeConnections = new List();\n\n            serverPort = Properties.Settings.Default.LastPort;\n            textBoxPort.Text = serverPort.ToString();\n\n            runSendDataThread = false;\n\n        }\n\n        private void textBoxPort_PreviewTextInput(object sender, TextCompositionEventArgs e)\n        {\n            bool tmpParse = false;\n            {\n                float tmpF;\n                var tmp = textBoxPort.Text + e.Text;\n                tmpParse = Single.TryParse(tmp, out tmpF);\n            }\n            e.Handled = !tmpParse;\n        }\n\n        public class StateObject\n        {\n            public Socket workSocket = null;\n            public const int BufferSize = 1024;\n            public byte&#091;] buffer = new byte&#091;BufferSize];\n            public StringBuilder sb = new StringBuilder();\n            public bool sendDataFlag = false;\n        }\n\n\n        public void StartListening()\n        {\n            IPAddress ipAddress = IPAddress.Parse(GetIPAddress(\"localhost\"));\n            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, serverPort);\n            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n            try\n            {\n                listener.Bind(localEndPoint);\n                listener.Listen(100);\n                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);\n            }\n            catch (Exception e)\n            {\n                Console.WriteLine(e.ToString());\n            }\n\n        }\n\n        public void StopListening()\n        {\n            listener.Close();\n            listener = null;\n        }\n\n        public void AcceptCallback(IAsyncResult ar)\n        {\n            try\n            {\n                Socket listener = (Socket)ar.AsyncState;\n                Socket handler = listener.EndAccept(ar);\n                StateObject state = new StateObject();\n                state.workSocket = handler;\n                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,\n                    new AsyncCallback(ReadCallback), state);\n                activeConnections.Add(state);\n                ChangeConnectionNumber();\n                Console.WriteLine(\"there is {0} connections\", activeConnections.Count);\n                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);\n            }\n            catch (System.ObjectDisposedException)\n            {\n                System.Console.WriteLine(\"Connection closed.\");\n                return;\n            }\n\n        }\n\n        public void ReadCallback(IAsyncResult ar)\n        {\n            String content = String.Empty;\n            StateObject state = (StateObject)ar.AsyncState;\n            Socket handler = state.workSocket;\n            try\n            {\n                int bytesRead = handler.EndReceive(ar);\n                if (bytesRead > 0)\n                {\n                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));\n                    content = state.sb.ToString();\n                    if (content.IndexOf(\"\\n\") > -1 || content.IndexOf(\"\") > -1)\n                    {\n                        string getString = content.Replace(\"\\r\", \"\").Replace(\"\\n\", \"\");\n                        if (getString == \"Start\")\n                        {\n                            Console.WriteLine(\"Start sending data\");\n                            state.sendDataFlag = true;\n                        }\n                        else if (getString == \"Stop\")\n                        {\n                            Console.WriteLine(\"Stop sending data\");\n                            state.sendDataFlag = false;\n                        }\n                        state.sb.Length = 0; ;\n                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,\n                            new AsyncCallback(ReadCallback), state);\n                    }\n                    else\n                    {\n                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,\n                            new AsyncCallback(ReadCallback), state);\n                    }\n                }\n                if (bytesRead == 0)\n                {\n                    lock (lockObjectConnection)\n                    {\n                        Console.WriteLine(\"Disconnected?\");\n                        activeConnections.Remove(state);\n                        ChangeConnectionNumber();\n\n                    }\n                }\n            }\n            catch (Exception e)\n            {\n                lock (lockObjectConnection)\n                {\n                    Console.WriteLine(e.Message);\n                    activeConnections.Remove(state);\n                    ChangeConnectionNumber();\n                }\n            }\n\n        }\n\n        private void Send(Socket handler, String data)\n        {\n            byte&#091;] byteData = Encoding.ASCII.GetBytes(data);\n            handler.BeginSend(byteData, 0, byteData.Length, 0,\n                new AsyncCallback(SendCallback), handler);\n        }\n\n        private void SendCallback(IAsyncResult ar)\n        {\n            try\n            {\n                Socket handler = (Socket)ar.AsyncState;\n                int bytesSent = handler.EndSend(ar);\n\n            }\n            catch (Exception e)\n            {\n                Console.WriteLine(e.ToString());\n            }\n        }\n\n        private void SendMessageThread()\n        {\n            while (runSendDataThread == true)\n            {\n                try\n                {\n                    lock (lockObjectConnection)\n                    {\n                        foreach (StateObject each in activeConnections)\n                        {\n                            if (each.sendDataFlag == true)\n                            {\n                                Send(each.workSocket, \"Connected\\n\");\n                            }\n                        }\n                    }\n                }\n                catch (Exception e)\n                {\n                    Console.WriteLine(e.Message);\n                }\n                Thread.Sleep(1000);\n            }\n            lock (lockObjectConnection)\n            {\n                foreach (StateObject each in activeConnections)\n                {\n                    each.workSocket.Close();\n                }\n            }\n        }\n\n\n        private string GetIPAddress(string hostname)\n        {\n            IPHostEntry host;\n            host = Dns.GetHostEntry(hostname);\n\n            foreach (IPAddress ip in host.AddressList)\n            {\n                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)\n                {\n                    return ip.ToString();\n                }\n            }\n            return string.Empty;\n        }\n\n        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n        {\n            runSendDataThread = false;\n            Properties.Settings.Default.LastPort = serverPort;\n            Properties.Settings.Default.Save();\n        }\n\n        private void buttonServerStart_Click(object sender, RoutedEventArgs e)\n        {\n            int tmpPort = 0;\n            if(int.TryParse(textBoxPort.Text, out tmpPort) == false)\n            {\n                return;\n            }\n            serverPort = tmpPort;\n            if (runSendDataThread == false)\n            {\n                ChangeConnectionNumber();\n                buttonServerStart.Content = \"Stop\";\n                StartListening();\n                runSendDataThread = true;\n                sendTouchDataThread = new Thread(new ThreadStart(SendMessageThread));\n                sendTouchDataThread.Start();\n            }\n            else\n            {\n                runSendDataThread = false;\n                sendTouchDataThread.Join();\n                sendTouchDataThread = null;\n                StopListening();\n                lock (lockObjectConnection)\n                {\n                    activeConnections.RemoveRange(0, activeConnections.Count);\n                }\n                buttonServerStart.Content = \"Start\";\n\n\n                ChangeConnectionNumber();\n\n            }\n        }\n\n        public void ChangeConnectionNumber()\n        {\n            var dispatcher = System.Windows.Application.Current.Dispatcher;\n            if (dispatcher.CheckAccess())\n            {\n                labelNum.Content = \"Num. of connection: \" + activeConnections.Count.ToString();\n            }\n            else\n            {\n                dispatcher.Invoke(() =>\n                {\n                    labelNum.Content = \"Num. of connection: \" + activeConnections.Count.ToString();\n                });\n            }\n        }\n}<\/code><\/pre>\n\n\n\n<p><div class=\"my-ad-space\">\n<div class=\"my-ad-label\">\u30b9\u30dd\u30f3\u30b5\u30fc\u30ea\u30f3\u30af<\/div>\n<div>\n\n<script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script>\n<!-- \u30ec\u30b9\u30dd\u30f3\u30b7\u30d6 -->\n<ins class=\"adsbygoogle\"\n     style=\"display:block\"\n     data-ad-client=\"ca-pub-1956541408145992\"\n     data-ad-slot=\"6517671867\"\n     data-ad-format=\"auto\"><\/ins>\n<script>\n(adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n\n<\/div>\n<\/div>\n<br><br><div class=\"ad-space-bottom\">\n      <div class=\"ad-label\">\u30b9\u30dd\u30f3\u30b5\u30fc\u30ea\u30f3\u30af<\/div>\n\n<script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script>\n<!-- \u30ec\u30b9\u30dd\u30f3\u30b7\u30d6 -->\n<ins class=\"adsbygoogle\"\n     style=\"display:block\"\n     data-ad-client=\"ca-pub-1956541408145992\"\n     data-ad-slot=\"6517671867\"\n     data-ad-format=\"auto\"><\/ins>\n<script>\n(adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n\n<\/div><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u3053\u308c\u307e\u3067\u5927\u4f53\u30bd\u30b1\u30c3\u30c8\u901a\u4fe1\u306f\u540c\u671f\u51e6\u7406\u3067\u3084\u3063\u3066\u305f\u3093\u3060\u3051\u3069\u3001\u975e\u540c\u671f\u3067\u306e\u30bd\u30b1\u30c3\u30c8\u901a\u4fe1\u304c\u3057\u305f\u304f\u306a\u3063\u305f\u306e\u3067\u307e\u3068\u3081\u3066\u307f\u305f\u3002\u3068\u306f\u3044\u3048\u3001\u524d\u56de\u306eTouchence\u306e\u30b5\u30f3\u30d7\u30eb\u3067\u4f7f\u3063\u3066\u3044\u308b\u90e8\u5206\u3092\u5207\u308a\u51fa\u3057\u305f\u611f\u3058\u3002<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-492","post","type-post","status-publish","format-standard","hentry","category-c"],"_links":{"self":[{"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/posts\/492","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/comments?post=492"}],"version-history":[{"count":7,"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/posts\/492\/revisions"}],"predecessor-version":[{"id":511,"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/posts\/492\/revisions\/511"}],"wp:attachment":[{"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/media?parent=492"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/categories?post=492"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/masahiroshiomi.jp\/blog\/wp-json\/wp\/v2\/tags?post=492"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}