当前位置: 首页>>代码示例>>C#>>正文


C# WebSocketServer.Start方法代码示例

本文整理汇总了C#中WebSocketServer.Start方法的典型用法代码示例。如果您正苦于以下问题:C# WebSocketServer.Start方法的具体用法?C# WebSocketServer.Start怎么用?C# WebSocketServer.Start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在WebSocketServer的用法示例。


在下文中一共展示了WebSocketServer.Start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        public static void Main(string [] args)
        {
            var wssv = new WebSocketServer (4649);
              //var wssv = new WebSocketServer (4649, true);
              //var wssv = new WebSocketServer ("ws://localhost:4649");
              //var wssv = new WebSocketServer ("wss://localhost:4649");
              #if DEBUG
              wssv.Log.Level = LogLevel.TRACE;
              #endif
              //var cert = ConfigurationManager.AppSettings ["ServerCertFile"];
              //var password = ConfigurationManager.AppSettings ["CertFilePassword"];
              //wssv.Certificate = new X509Certificate2 (cert, password);
              //wssv.KeepClean = false;
              wssv.AddWebSocketService<Echo> ("/Echo");
              wssv.AddWebSocketService<Chat> ("/Chat");
              //wssv.AddWebSocketService<Chat> ("/Chat", () => new Chat ("Anon#"));
              //wssv.AddWebSocketService<Echo> ("/エコー");
              //wssv.AddWebSocketService<Chat> ("/チャット");

              wssv.Start ();
              if (wssv.IsListening)
              {
            Console.WriteLine (
              "A WebSocket Server listening on port: {0} service paths:", wssv.Port);

            foreach (var path in wssv.WebSocketServices.ServicePaths)
              Console.WriteLine ("  {0}", path);
              }

              Console.WriteLine ("\nPress Enter key to stop server...");
              Console.ReadLine ();

              wssv.Stop ();
        }
开发者ID:kevleyski,项目名称:websocket-sharp,代码行数:34,代码来源:Program.cs

示例2: Main

        public static void Main()
        {
            var server = new WebSocketServer("127.0.0.1", 8080);
            server.Started += (sender, args) => Console.WriteLine("Server started!");
            server.Stopped += (sender, args) => Console.WriteLine("Server stopped!");

            Console.WriteLine("Tully WebSocket server at your command");
            var exit = false;
            server.Start();

            while (!exit)
            {
                var cmd = Console.ReadLine();

                switch (cmd)
                {
                    case "/exit":
                        exit = true;
                        break;
                    case "/start":
                        server.Start();
                        break;
                    case "/stop":
                        server.Stop();
                        break;
                    default:
                        Console.WriteLine("Unknown command " + cmd);
                        break;
                }
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
开发者ID:Domeee,项目名称:websockets,代码行数:34,代码来源:Program.cs

示例3: Awake

        public void Awake()
        {
            // Just in case cancel all old invokes related to this instance
            CancelInvoke ();

            // Do a full sync
            //FullSync ();

            // Add all vessels to the vessel list
            foreach (Vessel vessel in FlightGlobals.Vessels) {
                if (!all_vessels.Contains (vessel)) {
                    all_vessels.Add (vessel);
                }
            }
            InvokeRepeating ("UpdateClients",1.0F,1.0F);

            if (wssv == null) {
                Debug.Log ("Establishing websocket");
                wssv = new WebSocketServer (12321); //TODO: Add possibility to configure IP
                wssv.AddWebSocketService<MissionControlService> ("/mcs", () => new MissionControlService (this));
                wssv.Start ();

                Debug.Log ("Established websocket!");
            }
        }
开发者ID:voneiden,项目名称:ksp-missioncontrol,代码行数:25,代码来源:MissionControl.cs

示例4: MainWindow

 public MainWindow()
 {
     InitializeComponent();
     wsServer = new WebSocketServer(IPAddress.Parse("127.0.0.1"), 1234);
     wsServer.AddWebSocketService<Echo>("/");
     wsServer.Start();
 }
开发者ID:NIAEFEUP,项目名称:Kommando,代码行数:7,代码来源:MainWindow.xaml.cs

示例5: SetUp

 public void SetUp()
 {
     server = new WebSocketServer(URI.Port);
     server.AddService<Echo>(URI.AbsolutePath);
     server.Start();
     handle = new EventWaitHandle(false, EventResetMode.AutoReset);
 }
开发者ID:wsky,项目名称:top-link,代码行数:7,代码来源:WebSocketChannelTest.cs

示例6: WebSocketInterface

        public WebSocketInterface(int port, Session session)
        {
            _session = session;
            var translations = session.Translation;
            _server = new WebSocketServer();
            _websocketHandler = WebSocketEventManager.CreateInstance();
            var setupComplete = _server.Setup(new ServerConfig
            {
                Name = "NecroWebSocket",
                Ip = "Any",
                Port = port,
                Mode = SocketMode.Tcp,
                Security = "tls",
                Certificate = new CertificateConfig
                {
                    FilePath = @"cert.pfx",
                    Password = "necro"
                }
            });

            if (setupComplete == false)
            {
                Logger.Write(translations.GetTranslation(TranslationString.WebSocketFailStart, port), LogLevel.Error);
                return;
            }

            _server.NewMessageReceived += HandleMessage;
            _server.NewSessionConnected += HandleSession;

            _server.Start();
        }
开发者ID:RedNax67,项目名称:NecroBot,代码行数:31,代码来源:WebSocketInterface.cs

示例7: Run

        public void Run()
        {
            //websocket init
            Console.WriteLine("tetris server is starting... port:{0}", Port_WebSocket);
            var listener = new WebSocketServer();
            listener.NewMessageReceived += listener_NewMessageReceived;
            listener.NewSessionConnected += listener_NewSessionConnected;

            if (!listener.Setup(Port_WebSocket))
            {
                Console.WriteLine("failed to initialize.");
                return;
            }

            if (!listener.Start())
            {
                Console.WriteLine("failed to start.");
                return;
            }

            //transceiver init
            Console.WriteLine("transceiver is starting... port:{0}", Port_Transceiver);
            var tr = new Transceiver(null, 2013);

            isRunning = true;
            Thread th = new Thread(() =>
            {
                Packet p = new Packet();
                while (isRunning)
                {
                    p.Clear();
                    tr.Receive(ref p);

                    Console.WriteLine("received a packet: {0}", p.Peek());

                    if (conn != null)
                    {
                        try
                        {
                            conn.Send((string)p.Pop());
                        }
            #pragma warning disable 0168
                        catch (Exception ex)
                        {
                            //conn = null;
                        }
            #pragma warning restore 0168
                    }
                }
                tr.Dispose();
            });
            th.Start();

            Console.WriteLine("press enter to terminate server.");
            Console.ReadLine();

            isRunning = false;
            listener.Stop();
            Console.WriteLine("terminating server...");
        }
开发者ID:Letractively,项目名称:sod-lg-smart-tv-project,代码行数:60,代码来源:TetrisWebSocket.cs

示例8: Main

        static void Main()
        {
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://localhost:8181");
            server.Start(socket =>
                {
                    socket.OnOpen = () =>
                        {
                            Console.WriteLine("Open!");
                            allSockets.Add(socket);
                        };
                    socket.OnClose = () =>
                        {
                            Console.WriteLine("Close!");
                            allSockets.Remove(socket);
                        };
                    socket.OnMessage = message =>
                        {
                            Console.WriteLine(message);
                        };
                });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }
        }
开发者ID:emiaj,项目名称:Fleck,代码行数:32,代码来源:Server.cs

示例9: Start

 public void Start(string address, int port, string path)
 {
     IPAddress ipaddr = new IPAddress(address.Split('.').Select(a => (byte)a.to_i()).ToArray());
     WebSocketServer wss = new WebSocketServer(ipaddr, port, this);
     wss.AddWebSocketService<ServerReceiver>(path);
     wss.Start();
 }
开发者ID:cliftonm,项目名称:clifton,代码行数:7,代码来源:WebSocketServerService.cs

示例10: Initialize

	private static void Initialize () {
		wsServer = new WebSocketServer(
			WebConsoleDefinitions.SERVE_PROTOCOL + WebConsoleDefinitions.SERVE_ADDRESS + ":" + WebConsoleDefinitions.SERVE_PORT
		);
		wsServer.AddWebSocketService<WSServerInstance>("/");
		wsServer.Start();
	}
开发者ID:sassembla,项目名称:Unidon,代码行数:7,代码来源:ServerInitializer.cs

示例11: Start

        public void Start()
        {
            try
            {
                var socketServer = new WebSocketServer(this._port, this._isSSL);
                socketServer.AddWebSocketService<WSClientBehaviour>(this._path);
                if (this._isSSL)
                {
                    //configure SSL for websocket server (just to test this feature!)
                    string basedir = AppDomain.CurrentDomain.BaseDirectory;
                    string certPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(basedir, @"..\serverCertificate.pfx"));
                    if (!System.IO.File.Exists(certPath))
                        throw new Exception("I did not found the SSL certificate for the websocket server");
                    var passwd = "password";
                    socketServer.SslConfiguration.ServerCertificate = new X509Certificate2(certPath, passwd);
                }
               
                socketServer.Log.Output = (logData, msg) =>
                {
                    if (logData.Level == LogLevel.Error || logData.Level == LogLevel.Fatal)
                       this.OnError(new Exception(logData.Message));
                };
               
                this._socketServer = socketServer;
                socketServer.Start();

                MessageService.Start(this);
            }
            catch (Exception ex)
            {
                this.OnError(ex);
            }
        }
开发者ID:cbsistem,项目名称:JRIAppTS,代码行数:33,代码来源:WebSockectService.cs

示例12: Setup

        public void Setup()
        {
            _symbols = new List<Symbol>()
            {
                Symbol.Create("AAPL", SecurityType.Equity, Market.USA),
                Symbol.Create("AIG", SecurityType.Equity, Market.USA)
            };

            Config.Set("live-data-url", "ws://127.0.0.1");
            Config.Set("live-data-port", "8080");

            _mockServerBehavior = new MockServerBehavior();
            _dataQueueHandler = new ApiDataQueueHandler();
            var liveDataUri = new Uri(Config.Get("live-data-url"));
            var uriBuilder = new UriBuilder(liveDataUri);
            uriBuilder.Port = Config.GetInt("live-data-port");

            Task.Run(() =>
            {
                _mockServer = new WebSocketServer(uriBuilder.ToString());
                _mockServer.AddWebSocketService("/", () => _mockServerBehavior);

                Log.Trace("ApiDataQueueHandlerTests.Setup(): Starting the mock server.");
                _mockServer.Start();

                while (true)
                {
                    Thread.Sleep(1000);
                }
            });
        }
开发者ID:AlexCatarino,项目名称:Lean,代码行数:31,代码来源:ApiDataQueueHandlerTests.cs

示例13: Main

        static void Main(string[] args)
        {
            var config = new ServerConfig {
                Name = "SuperWebSocket",
                Ip = "Any",
                Port = 2012,
                Mode = SocketMode.Tcp,
            };

            Console.WriteLine("Starting WebSocketServer on port " + config.Port + "...");

            var socketServer = new WebSocketServer();
            socketServer.Setup(new RootConfig(), config);

            socketServer.NewMessageReceived += new SessionHandler<WebSocketSession, string>(socketServer_NewMessageReceived);
            socketServer.NewSessionConnected += new SessionHandler<WebSocketSession>(socketServer_NewSessionConnected);
            socketServer.SessionClosed += new SessionHandler<WebSocketSession, CloseReason>(socketServer_SessionClosed);

            if (!socketServer.Start()) {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("The server started successfully, press 'q' key to stop it!");

            while (Console.ReadKey().KeyChar != 'q') {
                Console.WriteLine();
                continue;
            }
            socketServer.Stop();

            Console.WriteLine("\nThe server stopped!");
        }
开发者ID:Psyborx,项目名称:c-sharp-websocket-test,代码行数:34,代码来源:Program.cs

示例14: Main

        static void Main(string[] args)
        {
            var webSocketServer = new WebSocketServer("ws://localhost:8081");
            var sockets = new List<IWebSocketConnection>();

            webSocketServer.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    sockets.Add(socket);
                };

                socket.OnMessage = mensagem =>
                {
                    foreach (var s in sockets)
                    {
                        s.Send(mensagem);
                    }
                };

                socket.OnClose = () =>
                {
                    sockets.Remove(socket);
                };
            });

            Console.ReadKey();
        }
开发者ID:jean-lourenco,项目名称:FleckWebSocketDemo,代码行数:28,代码来源:Program.cs

示例15: BasicRoundTrip

		public void BasicRoundTrip()
		{
			var serializer = new JsonCommonSerializer();

			var port = new Random().Next(6000, 60000);

			var listener = new WebSocketServer("ws://localhost:" + port);
			var serverTransport = listener.GenerateTransportSource("/p1");
			var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
			serverRouter.AddService<IMyService>(new MyService());
			listener.Start();

			var client = new WebSocket("ws://localhost:" + port + "/p1");
			var clientTransport = client.GenerateTransportSource();
			var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
			var proxy = clientRouter.AddInterface<IMyService>();
			client.Connect();

			var result = proxy.Add(3, 4).Result;
			Assert.Equal(7, result);

			clientRouter.Dispose();
			clientTransport.Dispose();
			client.Close();

			serverRouter.Dispose();
			serverTransport.Dispose();
			listener.Stop();
		}
开发者ID:BrannonKing,项目名称:Kts.Remoting,代码行数:29,代码来源:WebsocketSharpFullCircle.cs


注:本文中的WebSocketServer.Start方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。