public void Connect()
        {
            if (running)
            {
                Console.WriteLine("WebSocketServer already running");
                return;
            }
            try {
                _wsServer.Start((socket) => {
                    socket.OnOpen = () => {
                        Console.WriteLine("Client connected");
                        _connections.Add(socket);
                    };
                    socket.OnClose = () => {
                        Console.WriteLine("Client disconnected");
                        _connections.Remove(socket);
                    };
                    socket.OnMessage = (message) => {
                        OnMessage?.Invoke(message, socket);
                    };
                });

                Console.WriteLine("Server listens for websocket connections at: " + SOCKET_URL);
                running = true;
                OnServerStart?.Invoke();
            }
            catch (Exception e) {
                Console.WriteLine("Cannot start WebSocketServer.\n\tReason: " + e.Message +
                                  "\n\tTrying again in 10 seconds");

                Utils.setTimeout(() => {
                    Connect();
                }, 10 * 1000);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Starts the server
        /// </summary>
        public void Start()
        {
            if (_isBroadcasting)
            {
                return;
            }

            OnServerStart?.Invoke();

            _listener.Start();
            _isBroadcasting = true;

            //Start connection thread
            Thread t1 = new Thread(HandleConnection)
            {
                IsBackground = true,
                Name         = "Handle Connections"
            };

            //Start read thread
            Thread t2 = new Thread(Read)
            {
                IsBackground = true,
                Name         = "Read Clients"
            };

            t1.Start();
            t2.Start();
        }
Ejemplo n.º 3
0
 public SimpleTcpServer(int port, OnServerStart onStart, int bufferSize, OnClientConnected onClientConnected
                        , OnConnectionError onConnectionError, OnClientRequest onClientRequest, string endOfFileTag)
 {
     _onStart           = onStart;
     _bufferSize        = bufferSize;
     _onClientConnected = onClientConnected;
     _onConnectionError = onConnectionError;
     _onClientRequest   = onClientRequest;
     _endOfFileTag      = endOfFileTag;
     Port           = port;
     _activeClients = new List <TcpClient>();
     _tasks         = new List <Task>();
 }
Ejemplo n.º 4
0
            private void ListenClients <M>()
            {
                IsWorking = true;
                OnServerStart?.Invoke(this, new EventArgs());
                switch (AsyncWay)
                {
                case AsyncWay.Task:
                    Task.Run(() => AcceptClients <M>());
                    break;

                case AsyncWay.Thread:
                    Thread thread = new Thread(() => AcceptClients <M>());
                    thread.Start();
                    break;
                }
            }
Ejemplo n.º 5
0
 public void Start(IPEndPoint endPoint)
 {
     if (m_socket != null)
     {
         this.OnServerFail(new Exception("服務已存在"));
         return;
     }
     try
     {
         m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         m_socket.Bind(endPoint);
         m_socket.Listen(4096);
         StartAccept(null);
         OnServerStart?.Invoke();
     }
     catch (Exception ex)
     {
         OnServerFail?.Invoke(ex);
     }
 }
Ejemplo n.º 6
0
        public void Connect()
        {
            if (_running)
            {
                Console.WriteLine("WebSocketServer already running");
                return;
            }
            try {
                _server.StartAsync();
                _task = Task.Run(() => AcceptWebSocketClientsAsync(_server, _cancellation.Token));

                _running = true;
                OnServerStart?.Invoke();
            }
            catch (Exception e) {
                Console.WriteLine("Cannot start WebSocketServer.\n\tReason: " + e.Message +
                                  "\n\tTrying again in 10 seconds");

                Utils.setTimeout(() => {
                    Connect();
                }, 10 * 1000);
            }
        }
Ejemplo n.º 7
0
        private void runServerLoop(TcpListener srv, ILog lg)
        {
            IHttpService serv = m_service;

            arrReq           = new st_RequestHandle[1];
            arrReq[0].bufIn  = new byte[st_RequestHandle.SZ_BUF_IN];
            arrReq[0].bufOut = new byte[st_RequestHandle.SZ_BUF_OUT];

            System.Threading.Thread.Sleep(300);

            OnServerStart?.Invoke(this, null);
            while (!bStop)
            {
                try
                {
                    TcpClient tcpConn = srv.AcceptTcpClient();
                    handleRequest(tcpConn, ref arrReq[0], lg, serv);
                }
                catch (Exception ex)
                {
                    lg.log("TinyHttp.Accept", ex);
                }
            }
        }
Ejemplo n.º 8
0
 public void ServerStart()
 {
     OnServerStart?.Invoke();
 }
Ejemplo n.º 9
0
 public ServerCrossThread(OnClientConnect onConnect, OnServerStart onStart, MonoBehaviour parent)
 {
     this.onConnect = onConnect;
     this.onStart   = onStart;
     parent.StartCoroutine(Update());
 }
Ejemplo n.º 10
0
 public SimpleTcpServerCreator OnStart(OnServerStart onStart)
 {
     _onStart = onStart;
     return(this);
 }
Ejemplo n.º 11
0
        private async Task startServerAsync()
        {
            HttpListener httpListener = new HttpListener();

            httpListener.Prefixes.Add("http://*:" + Port + "/");
            try
            {
                httpListener.Start();
                HttpListenerResponse response = null;
                System.Diagnostics.Debug.WriteLine("DEBUGBACKEND::Start Listening...");
                OnServerStart?.Invoke(this, null);
                while (true)
                {
                    try
                    {
                        //HttpListenerContext context = httpListener.GetContext();
                        HttpListenerContext context = await httpListener.GetContextAsync();

                        HttpListenerRequest request  = context.Request;
                        string[]            segments = request.Url.Segments;
                        int  dataTypeInt             = 0;
                        bool hasDataType             = false;
                        foreach (string segment in segments)
                        {
                            Console.Write("(" + segment + ")");
                        }
                        response = context.Response;
                        if (segments[1] == "get/")
                        {
                            hasDataType = int.TryParse(segments[2], out dataTypeInt);
                            byte[] responseBuffer = null;
                            if (hasDataType)
                            {
                                if (latestControlMessage.ContainsKey(dataTypeInt))
                                {
                                    responseBuffer = Encoding.Default.GetBytes(latestControlMessage[dataTypeInt].ToString());
                                }
                                else
                                {
                                    responseBuffer = Encoding.Default.GetBytes("null");
                                }
                                response.ContentLength64 = responseBuffer.Length;
                                Stream output = response.OutputStream;
                                output.Write(responseBuffer, 0, responseBuffer.Length);
                            }
                            else if (segments[2].ToLower() == "buffer")
                            {
                                RCMWithEnqueueTime[] bufferArray;
                                lock (unfetchedControlMessageBufferLock)
                                {
                                    bufferArray = unfetchedControlMessageBuffer.ToArray();
                                    unfetchedControlMessageBuffer.Clear();
                                }

                                string s = "";
                                foreach (var buffer in bufferArray)
                                {
                                    s += buffer.RemoteXControlMessage.ToString();
                                    s += '/';
                                }
                                responseBuffer           = Encoding.Default.GetBytes(s);
                                response.ContentLength64 = responseBuffer.Length;
                                Stream output = response.OutputStream;
                                output.Write(responseBuffer, 0, responseBuffer.Length);
                            }
                            else if (segments[2].ToLower() == "serverqrcode.png")
                            {
                                response.ContentType = "image/png";
                            }
                        }
                    }
                    catch (HttpListenerException ex)
                    {
                        Console.WriteLine("ERROR IN RESPONSE AND REQUEST: " + ex.Message);
                    }
                    finally
                    {
                        if (response != null)
                        {
                            response.Close();
                        }
                    }
                }
            }
            catch (HttpListenerException ex)
            {
                Console.WriteLine("ERROR IN F*****G CONNECTION: " + ex.Message);
                OnServerFailed?.Invoke(this, null);
            }
            finally
            {
                httpListener.Close();
            }
        }