本文整理汇总了C#中WebSocketSharp.WebSocket.Send方法的典型用法代码示例。如果您正苦于以下问题:C# WebSocket.Send方法的具体用法?C# WebSocket.Send怎么用?C# WebSocket.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类WebSocketSharp.WebSocket
的用法示例。
在下文中一共展示了WebSocket.Send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConnectToWebSocket
public int ConnectToWebSocket()
{
ws = new WebSocket(_Address);
timer = new System.Windows.Forms.Timer();
timer.Interval = 1500;
timer.Tick += (sender, e) =>
{
if (ws != null)
ws.Send(JsonConvert.SerializeObject(new { type = "getframe" }));
};
ws.OnMessage += Ws_OnMessage;
ws.OnOpen += (sender, e) =>
{
//ws.Send(JsonConvert.SerializeObject(new { type = "getinfo" }));
string msg = "{\"type\":\"getinfo\"}";
ws.Send(msg);
};
ws.OnError += (sender, e) =>
{
MessageBox.Show("Error during Websocket Connection: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
ws.Close();
ws = null;
this.Dispose();
};
ws.Connect();
if (Connected != null)
Connected();
timer.Start();
return 0;
}
示例2: ScarletMetrics
/* WS */
public ScarletMetrics()
{
metricsws = new WebSocket("ws://" + MetricsWSURL + ":" + MetricsWSPort);
metricsws.Connect();
metricsws.OnOpen += (sender, e) =>
{
// Metrics - On Connection to the Metrics WS Reporting Server
// Need to include username / IP in here as well.
JsonObject jsonMessage = new JsonObject()
.add("type", "metrics")
.add("message", "connected");
metricsws.Send(jsonMessage.ToString());
};
metricsws.OnMessage += (sender, e) =>
{
};
metricsws.OnClose += (sender, e ) =>
metricsws.Connect();
metricsws.OnError += (sender, e) =>
metricsws.Connect();
}
示例3: HearbeatTransmitter
public HearbeatTransmitter(WebSocket socket, TimeSpan heartBeatInterval, Func<Dictionary<string, object>> onSendingHearbeat)
{
_socket = socket;
_heartBeatInterval = heartBeatInterval;
_onSendingHearbeat = onSendingHearbeat;
Receive<string>(message =>
{
if (socket.ReadyState == WebSocketState.Open)
{
var heartbeat = onSendingHearbeat();
heartbeat["$$Timestamp"] = DateTime.UtcNow;
var jsonPayload = JsonConvert.SerializeObject(new
{
Type = "Heartbeat",
Payload = heartbeat
});
socket.Send(jsonPayload);
Context.System.Scheduler.ScheduleTellOnce(heartBeatInterval, Self, "SendHeartbeat", Self);
}
}, msg => msg == "SendHeartbeat");
}
示例4: Main
public static void Main(string[] args)
{
if (args.Length != 1) {
Console.Error.WriteLine ("ERROR: need a valid Websocket URL");
Environment.Exit (-1);
}
using (var ws = new WebSocket (args[0])) {
Int64 syncCtr = 0;
ws.OnMessage += (sender, e) => {
Console.WriteLine (e.Data);
Interlocked.Decrement (ref syncCtr);
};
ws.Connect ();
if (!ws.IsAlive) {
Console.Error.WriteLine ("ERROR: Could not connect to Websocket Server {0}", args[0]);
Environment.Exit(-2);
}
var input = "";
while (string.Compare (input.Trim (), "shutdown", true) != 0) {
if (!string.IsNullOrWhiteSpace (input)) {
ws.Send (input.Trim());
Interlocked.Increment (ref syncCtr);
while (Interlocked.Read (ref syncCtr) > 0) {
Thread.Sleep (1);
}
}
Console.Write ("Type in a message or 'shutdown' to quit: ");
input = Console.ReadLine ();
} // Longevity loop
} // using
}
示例5: Main
static void Main(string[] args)
{
using (var ws = new WebSocket("ws://localhost:8080/spring-websocket-stomp-apollo/chat/websocket"))
{
ws.OnMessage += ws_OnMessage;
ws.OnOpen += ws_OnOpen;
ws.OnError += ws_OnError;
ws.Connect();
Thread.Sleep(1000);
StompMessageSerializer serializer = new StompMessageSerializer();
var connect = new StompMessage("CONNECT");
connect["accept-version"] = "1.2";
connect["host"] = "";
ws.Send(serializer.Serialize(connect));
var clientId = RandomString(5);
Console.WriteLine("Client Id :" + clientId);
Thread.Sleep(1000);
var sub = new StompMessage("SUBSCRIBE");
sub["id"] = "sub-0";
sub["destination"] = "/topic/broadcast";
ws.Send(serializer.Serialize(sub));
var sub1 = new StompMessage("SUBSCRIBE");
sub1["id"] = "sub-1";
sub1["destination"] = "/queue/message-" + clientId;
ws.Send(serializer.Serialize(sub1));
Thread.Sleep(1000);
var content = new Content(){ Subject ="Stomp client", Message = "Hello World!!"};
var broad = new StompMessage("SEND", JsonConvert.SerializeObject(content));
broad["content-type"] = "application/json";
broad["destination"] = "/app/broadcast";
ws.Send(serializer.Serialize(broad));
Console.ReadKey(true);
}
}
示例6: TestClient
static void TestClient()
{
using (var ws = new WebSocket("ws://localhost:8080/test1"))
{
ws.OnMessage += (sender, e) =>
Console.WriteLine("Laputa says: " + e.Data);
ws.Connect();
ws.Send("BALUS");
Console.ReadKey(true);
}
}
示例7: WebSocketSharpServer
public WebSocketSharpServer(ServerSettings settings) {
Settings = settings;
Server = new WebSocketServer(Settings.Port);
BaseUri = new Uri($"ws://localhost:{Server.Port}");
Server.Start();
Server.AddWebSocketService<Heartbeat>($"/{HeartbeatEndpoint}");
Heartbeat = new WebSocket($"{BaseUri}{HeartbeatEndpoint}");
Heartbeat.Connect();
Task.Factory.StartNew(() => {
while (!_isDisposing) {
Heartbeat.Send("Heartbeat OK");
Task.Delay(5000).Wait();
}
});
}
示例8: WebSocketClientConnection
public WebSocketClientConnection(string host, int port, int timeoutMillis)
: base(new WebSocketDevice(port, host))
{
this.timeout = timeoutMillis;
socket = new WebSocket("ws://" + host + ":" + port + "/");
socket.Log.Output = OnLog;
socket.OnMessage += OnMessageReceived;
socket.Connect();
CheckError();
// Say hi!
socket.Send("HI:" + uuid);
// Wait for hello...
WaitMessage();
}
示例9: EchoBack
static void EchoBack()
{
string res = null;
using (var ws = new WebSocket ("ws://echo.websocket.org"))
//using (var ws = new WebSocket ("ws://localhost:4649/Echo"))
{
var ver = Application.unityVersion;
ws.OnOpen += (sender, e) =>
ws.Send (String.Format ("Hello, Unity {0}!", ver));
ws.OnMessage += (sender, e) =>
res = e.Data;
ws.OnError += (sender, e) =>
Debug.LogError (e.Message);
ws.Connect ();
}
if (!res.IsNullOrEmpty())
EditorUtility.DisplayDialog ("Echo Back Successfully!", res, "OK");
}
示例10: ChatClient
public ChatClient(string url, string nick, string channel) {
webSocket = new WebSocket(url);
webSocket.OnOpen += (sender, e) =>
webSocket.Send("{\"cmd\":\"join\",\"channel\":\"" + channel + "\",\"nick\":\"" + nick + "\"}");
webSocket.OnMessage += (sender, args) => {
var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(args.Data);
if ((data["cmd"] as string == "chat") && (data["nick"] as string != nick)) {
System.Diagnostics.Debug.WriteLine(args.Data);
var chatArgs = new ChatEventArgs();
chatArgs.Text = data["text"] as string;
chatArgs.SenderNick = data["nick"] as string;
chatArgs.SenderTrip = data["trip"] as string;
//Console.WriteLine($"({data["trip"]}) {data["nick"]}: {data["text"]}");
OnChat?.Invoke(this, chatArgs);
}
};
webSocket.Connect();
}
示例11: GetClient
private static WebSocket GetClient(ServantConfiguration configuration)
{
var url = "ws://" + configuration.ServantIoUrl + "/Client?installationGuid=" + configuration.InstallationGuid + "&organizationGuid=" + configuration.ServantIoKey + "&servername=" + System.Environment.MachineName;
using (var ws = new WebSocket(url))
{
var serializer = new JavaScriptSerializer();
var pingTimer = new System.Timers.Timer(2000);
pingTimer.Elapsed += (sender, args) =>
{
ws.Ping();
};
pingTimer.Enabled = false;
ws.OnMessage += (sender, e) =>
{
var request = serializer.Deserialize<CommandRequest>(e.Data);
switch (request.Command)
{
case CommandRequestType.Unauthorized:
IsStopped = true;
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Servant.io key was not recognized.");
Console.ResetColor();
ws.Close();
break;
case CommandRequestType.GetSites:
var sites = SiteManager.GetSites();
var result = serializer.Serialize(sites);
ws.Send(serializer.Serialize(new CommandResponse(request.Guid)
{
Guid = request.Guid,
Message = result,
Success = true
}));
break;
case CommandRequestType.UpdateSite:
var site = serializer.Deserialize<Site>(request.JsonObject);
var originalSite = SiteManager.GetSiteByName(request.Value);
if (originalSite == null)
{
ws.Send("not_found");
return;
}
originalSite.ApplicationPool = site.ApplicationPool;
originalSite.Name = site.Name;
originalSite.SiteState = site.SiteState;
originalSite.Bindings = site.Bindings;
originalSite.LogFileDirectory = site.LogFileDirectory;
originalSite.SitePath = site.SitePath;
originalSite.Bindings = site.Bindings;
SiteManager.UpdateSite(originalSite);
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true}));
break;
case CommandRequestType.GetApplicationPools:
var appPools = SiteManager.GetApplicationPools();
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) {Message = serializer.Serialize(appPools), Success = true}));
break;
case CommandRequestType.GetCertificates:
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) {Message = serializer.Serialize(SiteManager.GetCertificates()), Success = true}));
break;
case CommandRequestType.StartSite:
var startSite = SiteManager.GetSiteByName(request.Value);
var startResult = SiteManager.StartSite(startSite);
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Success = startResult == SiteStartResult.Started, Message = startResult.ToString() }));
break;
case CommandRequestType.StopSite:
var stopSite = SiteManager.GetSiteByName(request.Value);
SiteManager.StopSite(stopSite);
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Success = true }));
break;
case CommandRequestType.RecycleApplicationPool:
var recycleSite = SiteManager.GetSiteByName(request.Value);
SiteManager.RecycleApplicationPoolBySite(recycleSite.IisId);
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
break;
case CommandRequestType.RestartSite:
var restartSite = SiteManager.GetSiteByName(request.Value);
SiteManager.RestartSite(restartSite.IisId);
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
break;
case CommandRequestType.DeleteSite:
var deleteSite = SiteManager.GetSiteByName(request.Value);
SiteManager.DeleteSite(deleteSite.IisId);
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = "ok", Success = true }));
break;
case CommandRequestType.CreateSite:
var createSite = serializer.Deserialize<Site>(request.JsonObject);
var id = SiteManager.CreateSite(createSite);
ws.Send(serializer.Serialize(new CommandResponse(request.Guid) { Message = id.ToString(), Success = true }));
break;
}
};
//.........这里部分代码省略.........
示例12: Main
public static void Main(string[] args)
{
var ts = new ThreadState();
WaitCallback notifyMsg = state =>
{
while (ts.Enabled || _msgQ.Count > 0)
{
Thread.Sleep(500);
if (_msgQ.Count > 0)
{
var msg = (NfMessage)_msgQ.Dequeue();
#if NOTIFY
var nf = new Notification(msg.Summary, msg.Body, msg.Icon);
nf.AddHint("append", "allowed");
nf.Show();
#else
Console.WriteLine("{0}: {1}", msg.Summary, msg.Body);
#endif
}
}
ts.Notification.Set();
};
ThreadPool.QueueUserWorkItem(notifyMsg);
using (var ws = new WebSocket("ws://echo.websocket.org", "echo"))
//using (var ws = new WebSocket("wss://echo.websocket.org", "echo"))
//using (var ws = new WebSocket("ws://localhost:4649"))
//using (var ws = new WebSocket("ws://localhost:4649/Echo"))
//using (var ws = new WebSocket("wss://localhost:4649/Echo"))
//using (var ws = new WebSocket("ws://localhost:4649/Echo?name=nobita"))
//using (var ws = new WebSocket("ws://localhost:4649/エコー?name=のび太"))
//using (var ws = new WebSocket("ws://localhost:4649/Chat"))
//using (var ws = new WebSocket("ws://localhost:4649/Chat?name=nobita"))
//using (var ws = new WebSocket("ws://localhost:4649/チャット?name=のび太"))
{
ws.OnOpen += (sender, e) =>
{
ws.Send("Hi, all!");
};
ws.OnMessage += (sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
enNfMessage("[WebSocket] Message", e.Data, "notification-message-im");
}
};
ws.OnError += (sender, e) =>
{
enNfMessage("[WebSocket] Error", e.Message, "notification-message-im");
};
ws.OnClose += (sender, e) =>
{
enNfMessage(
String.Format("[WebSocket] Close({0})", e.Code),
e.Reason,
"notification-message-im");
};
#if DEBUG
ws.Log.Level = LogLevel.TRACE;
#endif
//ws.Compression = CompressionMethod.DEFLATE;
//ws.Origin = "http://echo.websocket.org";
//ws.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
//{
// ws.Log.Debug(String.Format("\n{0}\n{1}", certificate.Issuer, certificate.Subject));
// return true;
//};
//ws.SetCookie(new Cookie("nobita", "\"idiot, gunfighter\""));
//ws.SetCookie(new Cookie("dora", "tanuki"));
ws.Connect();
//Console.WriteLine("Compression: {0}", ws.Compression);
Thread.Sleep(500);
Console.WriteLine("\nType \"exit\" to exit.\n");
string data;
while (true)
{
Thread.Sleep(500);
Console.Write("> ");
data = Console.ReadLine();
if (data == "exit")
//if (data == "exit" || !ws.IsAlive)
{
break;
}
ws.Send(data);
}
}
//.........这里部分代码省略.........
示例13: Main
public static void Main (string [] args)
{
using (var nf = new Notifier ())
using (var ws = new WebSocket ("ws://echo.websocket.org"))
//using (var ws = new WebSocket ("wss://echo.websocket.org")) // For Secure Connection
//using (var ws = new WebSocket ("ws://localhost:4649/Echo"))
//using (var ws = new WebSocket ("wss://localhost:4649/Echo"))
//using (var ws = new WebSocket ("ws://localhost:4649/Echo?name=nobita"))
//using (var ws = new WebSocket ("ws://localhost:4649/Chat"))
//using (var ws = new WebSocket ("wss://localhost:4649/Chat"))
//using (var ws = new WebSocket ("ws://localhost:4649/Chat?name=nobita"))
{
/* Setting WebSocket events */
ws.OnOpen += (sender, e) => ws.Send ("Hi, there!");
ws.OnMessage += (sender, e) =>
nf.Notify (
new NotificationMessage {
Summary = "WebSocket Message",
Body = e.Data,
Icon = "notification-message-im"
});
ws.OnError += (sender, e) =>
nf.Notify (
new NotificationMessage {
Summary = "WebSocket Error",
Body = e.Message,
Icon = "notification-message-im"
});
ws.OnClose += (sender, e) =>
nf.Notify (
new NotificationMessage {
Summary = String.Format ("WebSocket Close ({0})", e.Code),
Body = e.Reason,
Icon = "notification-message-im"
});
#if DEBUG
// Changing the logging level
ws.Log.Level = LogLevel.Trace;
#endif
// Setting Per-message Compression
//ws.Compression = CompressionMethod.Deflate;
/* For Secure Connection
ws.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
ws.Log.Debug (String.Format ("\n{0}\n{1}", certificate.Issuer, certificate.Subject));
return true; // If the server cert is valid
};
*/
// For HTTP Authentication (Basic/Digest)
//ws.SetCredentials ("nobita", "password", false);
// Setting Origin header
//ws.Origin = "http://echo.websocket.org";
//ws.Origin = "http://localhost:4649";
// Setting Cookies
//ws.SetCookie (new Cookie ("name", "nobita"));
//ws.SetCookie (new Cookie ("roles", "\"idiot, gunfighter\""));
// Setting Proxy
//ws.SetProxy ("http://localhost:3128", "nobita", "password");
// Connecting to the server
ws.Connect ();
//ws.ConnectAsync ();
Console.WriteLine ("\nType 'exit' to exit.\n");
while (true) {
Thread.Sleep (1000);
Console.Write ("> ");
var msg = Console.ReadLine ();
if (msg == "exit")
break;
// Sending a text message
ws.Send (msg);
}
}
}
示例14: Scarlet_WS_Initialise
public void Scarlet_WS_Initialise()
{
/* Scarlet Metrics */
wsm = new ScarletMetrics();
wsm.Send("Scarlet Service Started. (" + ip + ")");
/* Server */
var wssv = new WebSocketServer("ws://" + scarletURL + ":" + scarletPort);
wssv.AddWebSocketService<Link>("/");
wssv.Start();
/* Client */
ws = new WebSocket("ws://" + scarletURL + ":" + scarletPort);
ws.Connect();
ws.OnOpen += (sender, e) =>
{
ws.Send("Browser|Connected");
};
ws.OnMessage += (sender, e) =>
{
// Scarlet WS API
// Words = (Browser/Updater)|(IP/*)|(Command)|(Perameters)
string[] words = e.Data.Split('|');
if (words[0] == "Updater")
{
switch (words[1])
{
case ("browserConnect"):
Username = words[2];
key = ScarletAPI.Request("user", "info", words[2]);
if (backgroundWorker1.IsBusy == false)
{
ws.Send("Browser|browserConfirmation|free");
}
else
{
ws.Send("Browser|browserConfirmation|busy");
}
break;
case ("startDownload"):
installDirectory = words[2];
if (backgroundWorker1.IsBusy == false)
{
backgroundWorker1.RunWorkerAsync();
}
break;
case ("startVerify"):
verifyOnly = true;
installDirectory = words[2];
if (backgroundWorker1.IsBusy == false)
{
backgroundWorker1.RunWorkerAsync();
}
break;
case ("stopDownload"):
backgroundWorker1.CancelAsync();
break;
case ("locationChange"):
/*
installDirectory = words[2];
NameValueCollection postData = new NameValueCollection();
postData.Add("installDir", installDirectory);
ScarletAPI.PostRequest("user", "install", key, "", postData);
ws.Send("Browser|UpdateInstallLocation|" + installDirectory);
*/
ChooseFolder();
break;
case ("updateInstallLocation"):
installDirectory = words[2];
break;
case ("broadcast"):
broadcast(words[3]);
break;
case ("fetchStatus"):
pushStatusToBrowser();
break;
case ("quit"):
Application.Exit();
break;
//.........这里部分代码省略.........
示例15: button1_Click
private void button1_Click(object sender1, EventArgs e1)
{
try
{
string destIP = this.cmbIP.Text;
string patternIp = @"\b(([01]?\d?\d|2[0-4]\d|25[0-5])\.){3}([01]?\d?\d|2[0-4]\d|25[0-5])\b";
if (destIP.Length <= 0 || !Regex.IsMatch(destIP, patternIp))
{
return;
}
//ws = new WebSocket("ws://localhost:6110/Client");
ws = new WebSocket("ws://" + destIP + ":4650");
ws.OnOpen += (sender, e) =>
{
//ws.Send("Hi, all!");
Debug.WriteLine("OnOpen => ...");
};
ws.OnMessage += (sender, e) =>
{
string msg = e.Data;
Debug.WriteLine("OnMessage => " + msg);
command cmd_temp = (command)JsonConvert.DeserializeObject(msg, typeof(command));
IDevice device = findDevice(cmd_temp.TargetDevice);
if (device == null)
{
switch (cmd_temp.TargetDevice)
{
case TargetDeiveName.电风扇:
device = new FanDevice();
break;
case TargetDeiveName.电机:
device = new EngineDevice();
break;
case TargetDeiveName.绿灯:
device = new GreenLightDevice();
break;
case TargetDeiveName.红灯:
device = new RedLightDevice();
break;
case TargetDeiveName.黄灯:
device = new YellowLightDevice();
break;
case TargetDeiveName.GPS:
device = new GPSDevice();
break;
case TargetDeiveName.UHF:
device = new UHFDevice();
break;
}
}
if (device != null)
{
deviceList.Add(device);
device.setDevice(cmd_temp, cmd =>
{
string back = JsonConvert.SerializeObject(cmd);
Debug.WriteLine("***** OnMessage <= " + back);
ws.Send(back);
});
}
//ws.Send(JsonConvert.SerializeObject(cmd_temp));
};
ws.OnError += (sender, e) =>
{
Debug.WriteLine("OnError => " + e.Message);
};
ws.OnClose += (sender, e) =>
{
Debug.WriteLine("OnClose => " + e.Data);
};
ws.Connect();
//command cmd1 = new command(stateName.打开, "");
//cmd1.TargetDevice = TargetDeiveName.绿灯;
//cmd1.Initializing = "true";
//this.initialCommandList.Add(cmd1);
//sendInitialInfo(ws);
//MCserver = new WebSocketServer(MCServerUrl);
//MCserver.Start(socket =>
//{
// socket.OnOpen = () =>
// {
// host.OnOpenWebSocket(socket);
// };
// socket.OnClose = () =>
// {
// host.OnCloseWebSocket(socket);
// };
// socket.OnMessage = message =>
// {
// host.OnMessage(message, socket);
// };
//});
//.........这里部分代码省略.........