本文整理汇总了C#中WebSocket.Send方法的典型用法代码示例。如果您正苦于以下问题:C# WebSocket.Send方法的具体用法?C# WebSocket.Send怎么用?C# WebSocket.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类WebSocket
的用法示例。
在下文中一共展示了WebSocket.Send方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Play
public void Play()
{
var uri = new Uri(Server + "?user=" + Uri.EscapeDataString(UserName));
using (var socket = new WebSocket(uri))
{
socket.Connect();
while (!ShouldExit)
{
var response = socket.Recv();
if (!response.StartsWith(ResponsePrefix))
{
Console.WriteLine("Something strange is happening on the server... Response:\n{0}", response);
ShouldExit = true;
}
else
{
var boardString = response.Substring(ResponsePrefix.Length);
var action = DoMove(new GameBoard(boardString));
socket.Send(action);
}
}
}
}
示例2: ConnectToServer
//network
public static void ConnectToServer()
{
Game.GameState = Game.GameStateType.ConnectedToServer;
ws = new WebSocket("ws://127.0.0.1:8080", "echo-protocol"); //production: ws://ec2-54-227-104-51.compute-1.amazonaws.com:8080/
ws.OnOpen += (sender, e) =>
{
Debug.Log("connection with server opened");
if (ServerConnect != null) ServerConnect();
Loom.QueueOnMainThread(()=>{
ws.Send( JsonConvert.SerializeObject( new NetworkMsg(){ type = "connectRequest" }) );
});
};
ws.OnMessage += delegate(object sender, MessageEventArgs e) {
NetworkMsg ms = JsonConvert.DeserializeObject<NetworkMsg>(e.Data);
//Debug.Log("from: " + ms.id + " type: " + ms.type + " tata: " + ms.msg);
if (ServerMsg != null) ServerMsg(ms);
};
ws.OnError += delegate(object sender, ErrorEventArgs e) {
Debug.Log("error: " + e.Message);
if (ServerError!=null) ServerError();
};
ws.OnClose += delegate(object sender, CloseEventArgs e) {
Debug.Log("connection closed: " + e.Data);
if (ServerDisonnect!=null) ServerDisonnect();
};
ws.OnOpen+= delegate(object sender, System.EventArgs e) {
};
#if DEBUG
ws.Log.Level = LogLevel.TRACE;
#endif
ws.Connect();
}
示例3: WebSocketEndpoint
public WebSocketEndpoint()
{
var websocket = new WebSocket("ws://24.87.140.2:4000/", "basic");
websocket.OnOpen += (sender, args) =>
{
m_OpenEvent.Set();
return;
};
websocket.OnClose += (sender, args) =>
{
return;
};
websocket.OnMessage += (sender, args) =>
{
return;
};
websocket.Connect();
m_OpenEvent.WaitOne(1000);
websocket.Send("authenticate a b c");
}
示例4: ConnectToWebSocket
public static void ConnectToWebSocket()
{
WebSocket mySocket = new WebSocket();
mySocket.OpenEvent += new OpenEventHandler((object sender, OpenEventArgs e) =>
{
Console.WriteLine("Open Event");
mySocket.Send("Hello, World");
});
mySocket.MessageEvent += new MessageEventHandler((object sender,
MessageEventArgs e) =>
{
Console.WriteLine(e.Data);
});
mySocket.CloseEvent += new CloseEventHandler((object sender, CloseEventArgs e) =>
{
Console.WriteLine("Close Event");
});
mySocket.Connect("ws://localhost:8001/echo");
//mySocket.Close();
}
示例5: WsClient
public WsClient () {
bool success = TestConnection();
if (success) {
Debug.Log ("Server check ok");
string server = String.Format("wss://{0}:{1}/", ip, port );
using (conn = new WebSocket (server,"game"));
conn.Connect ();
conn.OnOpen += (sender, e) => conn.Send ("Server Connected");
conn.OnError += (sender, e) => {
Debug.Log("Websocket Error");
conn.Close ();
};
conn.OnClose += (sender, e) => {
Debug.Log("Websocket Close");
conn.Close ();
};
} else {
Debug.Log ("Server check failed");
return;
}
conn.SslConfiguration.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => {
// Do something to validate the server certificate.
Debug.Log ("Cert: " + certificate);
return true; // If the server certificate is valid.
};
}
示例6: OutgoingMessagePump
/// <summary>
/// Subscribes to the provided <paramref name="outgoing"/> stream, sending all events to the provided <paramref name="socket"/>.
/// </summary>
/// <param name="outgoing">The outgoing stream.</param>
/// <param name="socket">
/// The socket.
/// </param>
/// <returns>
/// The <see cref="Task"/> which will complete when either the observable completes (or errors) or the socket is closed (or errors).
/// </returns>
private static async Task OutgoingMessagePump(IObservable<string> outgoing, WebSocket socket)
{
var completion = new TaskCompletionSource<int>();
var subscription = new IDisposable[] { null };
Action complete = () =>
{
subscription[0]?.Dispose();
completion.TrySetResult(0);
};
// Until the socket is closed, pipe messages to it, then complete.
subscription[0] = outgoing.TakeWhile(_ => !socket.IsClosed).SelectMany(
next => socket.Send(ResponseKind.Next + next).ToObservable(),
error => socket.Send(ResponseKind.Error + JsonConvert.SerializeObject(error.ToDetailedString())).ToObservable(),
() =>
{
if (socket.IsClosed)
{
return Observable.Empty<Unit>();
}
// Send and close the socket.
var send = socket.Send(ResponseKind.Completed.ToString(CultureInfo.InvariantCulture)).ToObservable();
return send.SelectMany(_ => socket.Close((int)WebSocketCloseStatus.NormalClosure, "onCompleted").ToObservable());
}).Subscribe(_ => { }, _ => complete(), complete);
await completion.Task;
}
示例7: DisconnectSink
private void DisconnectSink(string error, WebSocket ws)
{
LogStreamerSession sink;
if (_children.TryGetValue(ws.ToUInt64(), out sink))
{
sink.Quit(error);
return;
}
ws.Send("!QUIT UnknownSocket");
ws.Disconnect("Unknown socket");
}
示例8: TestConnectWebSocket
public async Task TestConnectWebSocket()
{
var wsUrl = Resources.WsServerAddress + "test";
Assert.IsNotNull(WebServer.Module<WebSocketsModule>(), "WebServer has WebSocketsModule");
Assert.AreEqual(WebServer.Module<WebSocketsModule>().Handlers.Count, 1, "WebSocketModule has one handler");
#if NET46
var clientSocket = new ClientWebSocket();
var ct = new CancellationTokenSource();
await clientSocket.ConnectAsync(new Uri(wsUrl), ct.Token);
Assert.AreEqual(WebSocketState.Open, clientSocket.State, "Connection is open");
var message = new ArraySegment<byte>(System.Text.Encoding.Default.GetBytes("HOLA"));
var buffer = new ArraySegment<byte>(new byte[1024]);
await clientSocket.SendAsync(message, WebSocketMessageType.Text, true, ct.Token);
var result = await clientSocket.ReceiveAsync(buffer, ct.Token);
Assert.IsTrue(result.EndOfMessage, "End of message is true");
Assert.IsTrue(System.Text.Encoding.UTF8.GetString(buffer.Array).TrimEnd((char) 0) == "WELCOME", "Final message is WELCOME");
#else
var clientSocket = new WebSocket(wsUrl);
clientSocket.Connect();
Assert.AreEqual(WebSocketState.Open, clientSocket.State, "Connection is open");
clientSocket.Send("HOLA");
await Task.Delay(100);
#endif
}
示例9: Connect
void Connect(){
int id = (int)((1.0+Random.value)*0x10000);
ws = new WebSocket("ws://localhost:3000/websocket");
// called when websocket messages come.
ws.OnMessage += (sender, e) =>
{
//JSONObjectで解析
JSONObject json = new JSONObject(e.Data);
switch(json[0][0].str){
case "new_message":
messages.Add(string.Format("> {0}:{1}",json[0][1]["data"]["name"].str,
json[0][1]["data"]["body"].str));
if(messages.Count > 10){
messages.RemoveAt(0);
}
break;
case "websocket_rails.ping":
Debug.Log(string.Format("Send: [\"websocket_rails.pong\",{{\"id\":{0},\"data\":{{}}}}]", id));
ws.Send(string.Format("[\"websocket_rails.pong\",{{\"id\":{0},\"data\":{{}}}}]", id));
this.message = "";
break;
}
Debug.Log("Receive: " + e.Data);
};
ws.Connect();
Debug.Log("Connect to: " + ws.Url);
}