コード例 #1
0
        public void Close(string msg = null)
        {
            Error = msg;

            if (!string.IsNullOrEmpty(msg))
            {
                Log.d($"<color=#00ff00>[Server]:{Error}.</color>");
                OnError?.Invoke(msg);
            }

            ClientContainer.Dispose();

            if (token != null)
            {
                token.Cancel();
                token = null;
            }

            if (listener != null)
            {
                listener.Stop();
                listener = null;
                Log.d($"<color=#00ff00>[Server]:Shutdown().</color>");
            }
        }
コード例 #2
0
        public void Start(int port)
        {
            Debug.Assert(0 <= port && port <= 65535);
            Port = port;

            try {
                listener?.Stop();
                listener = new TcpListener(IPAddress.Any, Port);
                listener.Start();
            } catch (Exception e) {
                Close(e.Message);
                return;
            }

            Log.d($"<color=#00ff00>[Server]:Start({ClientName}:{Port}).</color>");

            token?.Cancel();
            token = new CancellationTokenSource();

            var context = SynchronizationContext.Current;

            Task.Run(() => {
                while (!token.IsCancellationRequested)
                {
                    try {
                        var client    = listener.AcceptTcpClient();
                        var container = ClientContainer.Create(client, context);
                        OnAcceptTcpClient?.Invoke(container);
                    } catch (Exception e) {
                        if (listener != null)
                        {
                            Close(e.Message);
                        }
                    }

                    Thread.Yield();
                }
            }, token.Token);
        }