本文整理匯總了C#中WebSocket4Net.WebSocket.Send方法的典型用法代碼示例。如果您正苦於以下問題:C# WebSocket.Send方法的具體用法?C# WebSocket.Send怎麽用?C# WebSocket.Send使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類WebSocket4Net.WebSocket
的用法示例。
在下文中一共展示了WebSocket.Send方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: RpcClient
public RpcClient(string ip, int port)
{
var uri = string.Format("ws://{0}:{1}/", ip, port);
_client = new WebSocket(uri);
_client.NoDelay = true;
_client.Opened += (sender, args) =>
Task.Run(() => DispatchConnected());
_client.Closed += (sender, args) =>
Task.Run(() => SafeCall(DispatchDisconnected));
Send = message => SafeCall(() =>
{
var data = RpcMessage.Write(message);
_client.Send(data);
});
_client.MessageReceived += (sender, args) => SafeCall(() =>
{
var data = args.Message;
var message = RpcMessage.Read(data);
Task.Run(() => ProcessMessage(message));
});
Task.Run(() => SafeCall(_client.Open));
}
示例2: Send
public static void Send(WebSocket ws, string channel, string message, int replyId = 1)
{
using (GetJsConfigScope())
{
var data = StringExtensions.ToJson(new SendMessage(channel, message, replyId));
limiter.Limit();
ws.Send(data);
}
}
示例3: PubSub
public void PubSub()
{
using (NetMQContext context = NetMQContext.Create())
{
using (WebSocket4Net.WebSocket webSocket = new WebSocket("ws://localhost:82", "WSNetMQ"))
{
using (WSPublisher publisher = context.CreateWSPublisher())
{
publisher.Bind("ws://localhost:82");
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
webSocket.Opened += (sender, args) => manualResetEvent.Set();
webSocket.Open();
webSocket.Error += (sender, args) => Console.WriteLine("Error");
manualResetEvent.WaitOne();
Assert.AreEqual(webSocket.State, WebSocketState.Open);
byte[] subscription = new byte[3];
subscription[0] = 0;
subscription[1] = 1;
subscription[2] = (byte)'H';
// should exit the router thread
webSocket.Send(subscription, 0, subscription.Length);
// wait for the subscription to arrive
Thread.Sleep(1000);
byte[] receivedMessage = null;
manualResetEvent.Reset();
webSocket.DataReceived += (sender, args) =>
{
receivedMessage = args.Data;
manualResetEvent.Set();
};
publisher.Send("Hello");
Assert.IsTrue(manualResetEvent.WaitOne(1000));
Assert.AreEqual(0, receivedMessage[0]);
Assert.AreEqual('H', receivedMessage[1]);
Assert.AreEqual('e', receivedMessage[2]);
Assert.AreEqual('l', receivedMessage[3]);
Assert.AreEqual('l', receivedMessage[4]);
Assert.AreEqual('o', receivedMessage[5]);
}
}
}
}
示例4: RequestReply
public void RequestReply()
{
using (NetMQContext context = NetMQContext.Create())
{
using (WebSocket4Net.WebSocket webSocket = new WebSocket("ws://localhost:82", "WSNetMQ"))
{
using (WSRouter router = context.CreateWSRouter())
{
router.Bind("ws://localhost:82");
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
webSocket.Opened += (sender, args) => manualResetEvent.Set();
webSocket.Open();
webSocket.Error += (sender, args) => Console.WriteLine("Error");
manualResetEvent.WaitOne();
Assert.AreEqual(webSocket.State, WebSocketState.Open);
byte[] message = new byte[2];
message[0] = 0;
message[1] = (byte)'H';
// should exit the router thread
webSocket.Send(message, 0, message.Length);
byte[] identity = router.Receive();
string msg = router.ReceiveString();
Assert.AreEqual("H", msg);
byte[] receivedMessage = null;
manualResetEvent.Reset();
webSocket.DataReceived += (sender, args) =>
{
receivedMessage = args.Data;
manualResetEvent.Set();
};
router.SendMore(identity).Send("W");
Assert.IsTrue(manualResetEvent.WaitOne(1000));
Assert.AreEqual(0 ,receivedMessage[0]);
Assert.AreEqual('W', receivedMessage[1]);
}
}
}
}
示例5: Main
static void Main(string[] args)
{
//ws://forever-alone.apphb.com/RecognizerService.ashx
var ws = new WebSocket("ws://forever-alone.apphb.com/RecognizerService.ashx");
ws.Opened += ws_Opened;
ws.Closed += ws_Closed;
ws.MessageReceived += ws_MessageReceived;
ws.DataReceived += ws_DataReceived;
ws.Open();
Console.ReadLine();
//ws.Send("Hai guys !");
var contents = File.ReadAllBytes("i_like_pickles.flac");
Console.WriteLine("Sent : {0}", contents.Length);
ws.Send(contents, 0, contents.Length);
Console.ReadLine();
}
示例6: TestConnection
public void TestConnection()
{
var webSocketClient = new WebSocket("ws://echo.websocket.org");
//webSocketClient.AllowUnstrustedCertificate = true;
webSocketClient.Opened += new EventHandler(webSocketClient_Opened);
webSocketClient.Closed += new EventHandler(webSocketClient_Closed);
webSocketClient.MessageReceived += new EventHandler<MessageReceivedEventArgs>(webSocketClient_MessageReceived);
webSocketClient.Open();
if (!m_OpenedEvent.WaitOne(5000))
{
Assert.Fail("Failed to Opened session ontime");
}
Assert.AreEqual(WebSocketState.Open, webSocketClient.State);
for (var i = 0; i < 10; i++)
{
var message = Guid.NewGuid().ToString();
webSocketClient.Send(message);
if (!m_MessageReceiveEvent.WaitOne(5000))
{
Assert.Fail("Failed to get echo messsage on time");
break;
}
Assert.AreEqual(m_CurrentMessage, message);
}
webSocketClient.Close();
if (!m_CloseEvent.WaitOne(5000))
{
Assert.Fail("Failed to close session ontime");
}
Assert.AreEqual(WebSocketState.Closed, webSocketClient.State);
}
示例7: ReportEventStats
public static void ReportEventStats(Message triggerMessage)
{
triggerMessage.Channel.SendMessage($"One moment {triggerMessage.User.GetUserName()}, and I'll check.");
var eventData = GetEventData();
if (eventData.IsFresh == false)
{
if (_socket == null)
{
_socket = new WebSocket("ws://10.0.0.100:29555/");
_socket.Opened += (sender, args) => _socket.Send("fetch");
_socket.Open();
}
else
{
_socket.Send("fetch");
}
}
var retries = 0;
var maxRetries = 5;
while (eventData.IsFresh == false && retries < maxRetries)
{
System.Threading.Thread.Sleep(2500);
eventData = GetEventData();
retries++;
}
if (retries == maxRetries)
{
triggerMessage.Channel.SendMessage($"Sorry {triggerMessage.User.GetUserName()}, I was unable to get fresh data.");
}
else
{
triggerMessage.Channel.SendMessage($"{eventData.Accepted} accepted, {eventData.Declined} declined, {eventData.Standby} standby, and {eventData.NoResponse} unsigned for the raid on the {eventData.NextRaidDate}.");
}
}
示例8: RequestFlickerConnection
public RequestFlickerConnection(string serviceName)
{
pingOk = true;
ServiceName = serviceName;
string url = GetRequestFlickerUrl();
websocket = new WebSocket(url);
websocket.Opened += websocket_Opened;
websocket.Error += websocket_Error;
websocket.Closed += websocket_Closed;
websocket.MessageReceived += websocket_MessageReceived;
t.Elapsed += (sender, args) =>
{
try
{
double totalMillisecondsSinceLastPing = (DateTime.Now - lastReceivedPong).TotalMilliseconds;
logger.Debug(string.Format("Checking pong received : {0}", totalMillisecondsSinceLastPing));
pingOk = totalMillisecondsSinceLastPing < 2 * checkTimeMs;
if (!pingOk)
{
logger.Debug(string.Format("Pong not Ok disconnecting."));
this.websocket.Close();
this.OnDisconnected.RaiseEvent(this,EventArgs.Empty);
}
else
{
websocket.Send("ping");
}
}
catch (Exception e)
{
logger.Info("Unable to send a ping : " + e.Message);
}
};
t.Start();
}
示例9: ConcurrentSendTest
public void ConcurrentSendTest()
{
WebSocket webSocketClient = new WebSocket(string.Format("{0}:{1}/websocket", Host, m_WebSocketServer.Config.Port), "basic", m_Version);
webSocketClient.AllowUnstrustedCertificate = true;
webSocketClient.Opened += new EventHandler(webSocketClient_Opened);
webSocketClient.Closed += new EventHandler(webSocketClient_Closed);
webSocketClient.Open();
if (!m_OpenedEvent.WaitOne(2000))
Assert.Fail("Failed to Opened session ontime");
string[] lines = new string[100];
for (int i = 0; i < lines.Length; i++)
{
lines[i] = Guid.NewGuid().ToString();
}
var messDict = lines.ToDictionary(l => l);
webSocketClient.MessageReceived += (s, m) =>
{
messDict.Remove(m.Message);
Console.WriteLine("R: {0}", m.Message);
};
Parallel.For(0, lines.Length, (i) =>
{
webSocketClient.Send("ECHO " + lines[i]);
});
int waitRound = 0;
while (waitRound < 10)
{
if (messDict.Count <= 0)
break;
Thread.Sleep(500);
waitRound++;
}
if (messDict.Count > 0)
{
Assert.Fail("Failed to receive message on time.");
}
webSocketClient.Close();
if (!m_CloseEvent.WaitOne(1000))
Assert.Fail("Failed to close session ontime");
}
示例10: SendDataTest
public void SendDataTest()
{
WebSocket webSocketClient = new WebSocket(string.Format("{0}:{1}/websocket", Host, m_WebSocketServer.Config.Port), "basic", m_Version);
if (!webSocketClient.SupportBinary)
return;
webSocketClient.AllowUnstrustedCertificate = true;
webSocketClient.Opened += new EventHandler(webSocketClient_Opened);
webSocketClient.Closed += new EventHandler(webSocketClient_Closed);
webSocketClient.DataReceived += new EventHandler<DataReceivedEventArgs>(webSocketClient_DataReceived);
webSocketClient.Open();
if (!m_OpenedEvent.WaitOne(2000))
Assert.Fail("Failed to Opened session ontime");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append(Guid.NewGuid().ToString());
}
string messageSource = sb.ToString();
Random rd = new Random();
for (int i = 0; i < 100; i++)
{
int startPos = rd.Next(0, messageSource.Length - 2);
int endPos = rd.Next(startPos + 1, messageSource.Length - 1);
string message = messageSource.Substring(startPos, endPos - startPos);
Console.WriteLine("Client:" + message);
var data = Encoding.UTF8.GetBytes(message);
webSocketClient.Send(data, 0, data.Length);
if (!m_MessageReceiveEvent.WaitOne(1000))
Assert.Fail("Cannot get response in time!");
Assert.AreEqual(message, m_CurrentMessage);
}
webSocketClient.Close();
if (!m_CloseEvent.WaitOne(1000))
Assert.Fail("Failed to close session ontime");
}
示例11: SendPingReactTest
public void SendPingReactTest()
{
WebSocket webSocketClient = new WebSocket(string.Format("{0}:{1}/websocket", Host, m_WebSocketServer.Config.Port), "basic", m_Version);
webSocketClient.AllowUnstrustedCertificate = true;
webSocketClient.Opened += new EventHandler(webSocketClient_Opened);
webSocketClient.Closed += new EventHandler(webSocketClient_Closed);
webSocketClient.MessageReceived += new EventHandler<MessageReceivedEventArgs>(webSocketClient_MessageReceived);
webSocketClient.Open();
if (!m_OpenedEvent.WaitOne(2000))
Assert.Fail("Failed to Opened session ontime");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append(Guid.NewGuid().ToString());
}
string messageSource = sb.ToString();
Random rd = new Random();
for (int i = 0; i < 10; i++)
{
int startPos = rd.Next(0, messageSource.Length - 2);
int endPos = rd.Next(startPos + 1, messageSource.Length - 1);
string message = messageSource.Substring(startPos, endPos - startPos);
Console.WriteLine("PING:" + message);
webSocketClient.Send("PING " + message);
}
Thread.Sleep(5000);
webSocketClient.Close();
if (!m_CloseEvent.WaitOne(1000))
Assert.Fail("Failed to close session ontime");
}
示例12: Main
static void Main(string[] args)
{
// remote sevice information
string remoteHost = "112.74.207.57";
//string remoteHost = "10.193.228.69"; //"a23126-04"; // 10.193.228.69
string remotePort = "2012";
// get default web proxy
//Uri serviceUrl = new Uri(string.Format("http://{0}", remoteHost));
Uri serviceUrl = new Uri(string.Format("http://www.baidu.com", remoteHost));
Uri proxyUri = WebRequest.DefaultWebProxy.GetProxy(serviceUrl);
if (serviceUrl == proxyUri)
{
proxyUri = null;
}
//wsClient = new WebSocket("ws://112.74.207.57:2012/");
//wsClient = new WebSocket("ws://112.74.207.5:2012/", version: WebSocketVersion.None,
//httpConnectProxy: new DnsEndPoint("wwwgate0.mot.com", 1080));
//wsClient = new WebSocket("ws://a23126-04:2012/", "", null, null, "", "", WebSocketVersion.None,
// new DnsEndPoint("wwwgate0.mot.com", 1080));
//List<KeyValuePair<String, String>> list_customHeaderItems = new List<KeyValuePair<string, string>>();
//String userName = "testuser1";
//String userPassword = "12345678";
//string authInfo = userName + ":" + userPassword;
//authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
//list_customHeaderItems.Add(new KeyValuePair<string, string>("Authorization", "Basic " + authInfo));
wsClient = new WebSocket(string.Format("ws://{0}:{1}/", remoteHost, remotePort));
//customHeaderItems: list_customHeaderItems);
if (proxyUri != null)
{
Console.WriteLine("use proxy: [" + proxyUri.ToString() + "]");
HttpConnectProxy proxy = new HttpConnectProxy(new DnsEndPoint(proxyUri.Host, proxyUri.Port));
wsClient.Proxy = proxy;
}
wsClient.Opened += wsClient_Opened;
wsClient.DataReceived += wsClient_DataReceived;
wsClient.MessageReceived += wsClient_MessageReceived;
wsClient.Closed += wsClient_Closed;
wsClient.Error += wsClient_Error;
wsClient.Open();
if (!OpenedEvent.WaitOne(5000))
{
Console.WriteLine("Failed to open!");
Console.ReadKey();
return;
}
Random rnd = new Random();
string msg = "echo " + rnd.Next(0, 100).ToString();
Console.WriteLine("sending msg ... [" + msg + "]");
wsClient.Send(msg);
Console.ReadKey();
}
示例13: CloseWebSocketTest
public void CloseWebSocketTest()
{
WebSocket webSocketClient = new WebSocket(string.Format("{0}:{1}/websocket", Host, m_WebSocketServer.Config.Port), "basic", m_Version);
webSocketClient.AllowUnstrustedCertificate = true;
webSocketClient.Opened += new EventHandler(webSocketClient_Opened);
webSocketClient.Closed += new EventHandler(webSocketClient_Closed);
webSocketClient.MessageReceived += new EventHandler<MessageReceivedEventArgs>(webSocketClient_MessageReceived);
webSocketClient.Open();
if (!m_OpenedEvent.WaitOne(2000))
Assert.Fail("Failed to Opened session ontime");
Assert.AreEqual(WebSocketState.Open, webSocketClient.State);
webSocketClient.Send("QUIT");
if (!m_CloseEvent.WaitOne(1000))
Assert.Fail("Failed to close session ontime");
Assert.AreEqual(WebSocketState.Closed, webSocketClient.State);
}
示例14: SendMessageTest
public void SendMessageTest()
{
WebSocket webSocketClient = new WebSocket(string.Format("ws://127.0.0.1:{0}/websocket", m_WebSocketServer.Config.Port), "basic", m_Version);
webSocketClient.Opened += new EventHandler(webSocketClient_Opened);
webSocketClient.Closed += new EventHandler(webSocketClient_Closed);
webSocketClient.MessageReceived += new EventHandler<MessageReceivedEventArgs>(webSocketClient_MessageReceived);
webSocketClient.Open();
if (!m_OpenedEvent.WaitOne(1000))
Assert.Fail("Failed to Opened session ontime");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append(Guid.NewGuid().ToString());
}
string messageSource = sb.ToString();
Random rd = new Random();
for (int i = 0; i < 100; i++)
{
int startPos = rd.Next(0, messageSource.Length - 2);
int endPos = rd.Next(startPos + 1, messageSource.Length - 1);
string message = messageSource.Substring(startPos, endPos - startPos);
webSocketClient.Send("ECHO " + message);
Console.WriteLine("Client:" + message);
if (!m_MessageReceiveEvent.WaitOne(1000))
Assert.Fail("Cannot get response in time!");
Assert.AreEqual(message, m_CurrentMessage);
}
webSocketClient.Close();
if (!m_CloseEvent.WaitOne(1000))
Assert.Fail("Failed to close session ontime");
}
示例15: Register
public override bool Register(string Username, string Password)
{
try
{
HttpWebRequest betrequest = (HttpWebRequest)HttpWebRequest.Create("https://www.bitdice.me/");
if (Prox != null)
betrequest.Proxy = Prox;
betrequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
betrequest.CookieContainer = new CookieContainer();
HttpWebResponse EmitResponse = (HttpWebResponse)betrequest.GetResponse();
string sEmitResponse = new StreamReader(EmitResponse.GetResponseStream()).ReadToEnd();
getcsrf(sEmitResponse);
getstream(sEmitResponse);
cookie = EmitResponse.Cookies["_csn_session"].Value;
if (Client != null)
Client.Close();
List<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>();
headers.Add(new KeyValuePair<string, string>("Cookie", "_csn_session=" + cookie));
Client = new WebSocket("wss://www.bitdice.me/stream/" + stream, "", null, headers, "dicebot", "http://bitdice.me", WebSocketVersion.Rfc6455);
Client.Opened += Client_Opened;
Client.Error += Client_Error;
Client.Closed += Client_Closed;
Client.MessageReceived += Client_MessageReceived;
Client.Open();
while (Client.State == WebSocketState.Connecting)
{
Thread.Sleep(100);
}
if (Client.State == WebSocketState.Open)
{
Client.Send("{\"jsonrpc\":\"2.0\",\"method\":\"user:update\",\"params\":{\"username\":\"" + Username + "\",\"user_seed\":\"1256e154283ea05b9538\",\"hide_bets_below\":\"0.0\",\"hide_other_bets\":false},\"id\":1}");
}
else
{
finishedlogin(false);
return false;
}
betrequest = (HttpWebRequest)HttpWebRequest.Create("https://www.bitdice.me/users/password");
betrequest.Method = "POST";
betrequest.CookieContainer = new CookieContainer();
string post = string.Format("user%5Bpassword%5D={0}&user%5Bpassword_confirmation%5D={0}", Password);
username = Username;
betrequest.ContentLength = post.Length;
if (Prox != null)
betrequest.Proxy = Prox;
betrequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
betrequest.CookieContainer.Add(new Cookie("_csn_session", cookie, "/", "bitdice.me"));
betrequest.Headers.Add("X-CSRF-Token", csrf);
using (var writer = new StreamWriter(betrequest.GetRequestStream()))
{
writer.Write(post);
}
EmitResponse = (HttpWebResponse)betrequest.GetResponse();
sEmitResponse = new StreamReader(EmitResponse.GetResponseStream()).ReadToEnd();
cookie = EmitResponse.Cookies["_csn_session"].Value;
betrequest = (HttpWebRequest)HttpWebRequest.Create("https://www.bitdice.me/");
if (Prox != null)
betrequest.Proxy = Prox;
betrequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
betrequest.CookieContainer = new CookieContainer();
betrequest.CookieContainer.Add(new Cookie("_csn_session", cookie, "/", "bitdice.me"));
EmitResponse = (HttpWebResponse)betrequest.GetResponse();
sEmitResponse = new StreamReader(EmitResponse.GetResponseStream()).ReadToEnd();
getDeposit(sEmitResponse);
getcsrf(sEmitResponse);
cookie = EmitResponse.Cookies["_csn_session"].Value;
getstream(sEmitResponse);
getcsrf(sEmitResponse);
getstream(sEmitResponse);
if (Client != null)
Client.Close();
headers = new List<KeyValuePair<string, string>>();
headers.Add(new KeyValuePair<string, string>("Cookie", "_csn_session=" + cookie));
Client = new WebSocket("wss://www.bitdice.me/stream/" + stream, "", null, headers, "dicebot", "http://bitdice.me", WebSocketVersion.Rfc6455);
Client.Opened += Client_Opened;
Client.Error += Client_Error;
Client.Closed += Client_Closed;
Client.MessageReceived += Client_MessageReceived;
Client.Open();
while (Client.State == WebSocketState.Connecting)
{
Thread.Sleep(100);
}
finishedlogin(Client.State == WebSocketState.Open);
return true;
}
//.........這裏部分代碼省略.........