本文整理汇总了C#中WebSocketServer类的典型用法代码示例。如果您正苦于以下问题:C# WebSocketServer类的具体用法?C# WebSocketServer怎么用?C# WebSocketServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WebSocketServer类属于命名空间,在下文中一共展示了WebSocketServer类的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 ();
}
示例2: 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!");
}
示例3: WebSocketInterface
public WebSocketInterface(int port)
{
_server = new WebSocketServer();
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($"Failed to start WebSocketServer on port : {port}", LogLevel.Error);
return;
}
_server.NewMessageReceived += HandleMessage;
_server.NewSessionConnected += HandleSession;
_server.Start();
}
示例4: Context
/// <summary>
/// Initializes a new instance of the <see cref="Context"/> class.
/// </summary>
public Context(WebSocketServer server, TcpClient connection)
{
Server = server;
Connection = connection;
Buffer = new byte[_bufferSize];
UserContext = new UserContext(this) {ClientAddress = connection.Client.RemoteEndPoint};
}
示例5: 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!");
}
}
示例6: 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();
}
示例7: 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();
}
}
示例8: 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();
}
示例9: 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);
}
});
}
示例10: Main
static void Main(string[] args)
{
//int port = int.Parse(args[0]);
int port = 443;
ServerConfig serverConfig = new ServerConfig
{
Name = "SecureSuperWebSocket",
Ip = "Any",
Port = port,
MaxRequestLength = 10485760,
SendingQueueSize = 500,
ReceiveBufferSize = 2050 * 1024,
//SendBufferSize = 600 * 1024,
};
socketServer = new WebSocketServer();
socketServer.NewSessionConnected += SocketServer_NewSessionConnected;
socketServer.NewDataReceived += SocketServer_NewDataReceived;
//socketServer.NewMessageReceived += SocketServer_NewMessageReceived;
socketServer.Setup(serverConfig);
socketServer.Start();
Console.WriteLine("Server is running on port {0} ...", port);
Console.ReadKey();
}
示例11: 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();
}
示例12: MainWindow
public MainWindow()
{
InitializeComponent();
wsServer = new WebSocketServer(IPAddress.Parse("127.0.0.1"), 1234);
wsServer.AddWebSocketService<Echo>("/");
wsServer.Start();
}
示例13: 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...");
}
示例14: 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();
}
示例15: Test1
static void Test1()
{
FleckLog.Level = LogLevel.Debug;
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);
allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
};
});
var input = Console.ReadLine();
while (input != "exit")
{
foreach (var socket in allSockets.ToList())
{
socket.Send(input);
}
input = Console.ReadLine();
}
}