本文整理汇总了C#中IWebSocketConnection.Send方法的典型用法代码示例。如果您正苦于以下问题:C# IWebSocketConnection.Send方法的具体用法?C# IWebSocketConnection.Send怎么用?C# IWebSocketConnection.Send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IWebSocketConnection
的用法示例。
在下文中一共展示了IWebSocketConnection.Send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Open
private static void Open(IWebSocketConnection socket)
{
//add our socket to a persistent collection so we can reference later
allSockets.Add(socket);
//create a strongly typed sockpuppet
IClientWindow puppet = SockPuppet.Puppet.New<IClientWindow>(r => socket.Send(r));
//add it to a dictionary so we can reference by socket id later
clientWindows.Add(socket.ConnectionInfo.Id, puppet);
//create a dynamic sockpuppet
dynamic dynamicPuppet = SockPuppet.Puppet.New(r => socket.Send(r));
//add it to a dictionary so we can reference by socket id later
clientDynamicWindows.Add(socket.ConnectionInfo.Id, dynamicPuppet);
Console.WriteLine("> Socket opened to " + socket.ConnectionInfo.ClientIpAddress);
}
示例2: SetupClient
private void SetupClient(IWebSocketConnection c)
{
c.OnOpen = () => {
Console.WriteLine("[" + c.ConnectionInfo.ClientIpAddress + "] connected");
clients.Add(c);
};
c.OnError = (ex) => { try { clients.Remove(c); } catch (Exception) { };};
c.OnClose = () => { try { clients.Remove(c); } catch (Exception) { };};
c.OnMessage = (s) => ReceivedClientMessage(c, s);
c.Send("welcome");
}
示例3: Client
static unsafe void Client(IWebSocketConnection conn)
{
CultureInfo culture = new System.Globalization.CultureInfo("en-US");
Console.WriteLine("handling client");
float w, x, y, z;
while (conn.IsAvailable)
{
OVR_Peek(&w, &x, &y, &z);
string ss = string.Format(culture,"{0},{1},{2},{3}", w,x,y,z);
conn.Send(ss);
System.Threading.Thread.Sleep(10);
}
}
示例4: startAuthentication
private void startAuthentication(String jsonMessage, IWebSocketConnection socket)
{
Guid socketID = socket.ConnectionInfo.Id;
Console.WriteLine("JSON: " + jsonMessage);
this.user = JsonConvert.DeserializeObject<User>(jsonMessage);
if (!isUserNameAlreadyInUse())
{
ludo.Users.Add(this.user);
Console.WriteLine("Online Users:");
for (int i = 0; i < ludo.Users.Count; i++)
{
Console.WriteLine("\t-" + ludo.Users[i].UserName);
}
}
else
{
socket.Send("Username is already in use");
}
}
示例5: Send
public void Send(IWebSocketConnection socket, object message)
{
socket.Send(Serialize(message));
}
示例6: Send
public void Send(IWebSocketConnection connectionToRecipient)
{
connectionToRecipient.Send(JsonConvert.SerializeObject(this, new IsoDateTimeConverter()));
}
示例7: startAuthentication
private void startAuthentication(String jsonMessage, IWebSocketConnection socket)
{
this.user = JsonConvert.DeserializeObject<User>(jsonMessage); // Serialize from Json to Object
this.user.SocketID = socket.ConnectionInfo.Id;
this.user.Handshaked = true;
if (isUserNameAvailable())
{
this.user.IsUserNameAvailable = true;
//this.user.IP = socket.ConnectionInfo.ClientIpAddress;
Main.ludo.Users.Add(this.user); // Add this User for the online user list
setUserListID();
socket.Send(JsonConvert.SerializeObject(this.user)); // Desiralize from Object to Json | Sending 1 user object
}
else
{
// Username isn't available
this.user.IsUserNameAvailable = false;
//this.user.UserListIndex = -1;
socket.Send(JsonConvert.SerializeObject(this.user));
}
}
示例8: populateQueueList
private void populateQueueList(IWebSocketConnection fromSocket)
{
string queueList = "{\"messageType\":\"listUpdate\",\"list\":\"queueList\",\"html\":\"" + Queue.Instance.queueListHTML() + "\"}";
fromSocket.Send(queueList);
}
示例9: SendErrorResponse
private static void SendErrorResponse(IWebSocketConnection socket, string errorInfo)
{
Logger.Instance().ErrorWithFormat("{0}:{1}, {2}", socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo, errorInfo);
var header = string.Format("{0}={1}", ServerDefines.CommandType, ServerDefines.Error);
var headerBytes = Encoding.UTF8.GetBytes(header);
var bodyBytes = string.IsNullOrEmpty(errorInfo) ? null : Encoding.UTF8.GetBytes(errorInfo);
var bytes = ResponseDataHelper.GenerateResponseData(headerBytes, bodyBytes);
socket.Send(bytes);
}
示例10: SendEvent
/// <summary>
/// Sends data to the socket in JSON format.
/// </summary>
private static void SendEvent(IWebSocketConnection socket, string @event, object data)
{
var msg = new
{
@event = @event,
data = data
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(msg);
socket.Send(json);
}
示例11: OnMessage
/// <summary>
/// Method called when the WebSocket receives a message.
/// </summary>
/// <param name="socket">The client socket the message comes from.</param>
/// <param name="message">The client message.</param>
private void OnMessage(IWebSocketConnection socket, string message)
{
// Timestamp containing the current time with the pattern: 2012-07-06 19:04:23
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
// Get user id from receivedJSON object
string uid = string.Empty;
// The chat message object with the ts (timestamp), uid (user id) and msg (message) properties.
ChatMessage chatMessage = new ChatMessage();
try
{
if (this.connectedSockets.ContainsKey(socket))
{
// Get the client user name
uid = this.connectedSockets[socket];
// Build the JSON object which will be send to all connected clients.
// It contains the current timestamp, the user name the message is
// came from and finally the message itself.
chatMessage.ts = timestamp;
chatMessage.uid = uid;
chatMessage.msg = message;
FleckLog.Info("Msg rcv: " + uid + " @ " + timestamp + " => " + message);
// Socket already stored in connected sockets and send its user name. So send
// assembled JSON object to all connected clients.
foreach (KeyValuePair<Fleck.IWebSocketConnection, string> client in this.connectedSockets)
{
client.Key.Send(JsonConvert.SerializeObject(chatMessage));
}
}
else
{
// First message from the socket => message contains the client user name.
// Check now if user name is available. If not, add socket to the connected
// sockets containing its user name.
if (!this.connectedSockets.ContainsValue(message))
{
// Store new connected client with its send user name to the connected sockets.
this.connectedSockets.Add(socket, message);
FleckLog.Info("Client <" + socket.ConnectionInfo.ClientIpAddress + "> set user name to <" + message + ">");
}
else
{
// Send client that the user name is already in use. The server now has
// to close the WebSocket to the client
chatMessage.ts = timestamp;
chatMessage.uid = message;
chatMessage.msg = "Error: the user name <" + message + "> is already in use!";
// Serialise ChatMessage object to JSON
socket.Send(JsonConvert.SerializeObject(chatMessage));
socket.Close();
// If socket is stored in connected sockets list, remove it
if (this.connectedSockets.ContainsKey(socket))
{
this.connectedSockets.Remove(socket);
}
}
}
}
catch (Exception e)
{
// WebSocket could not be bind. E.g. if the socket is already in use.
FleckLog.Error("Error opening WebSocket on <" + this.connectionInfo + ">. WebSocket maybe in use?");
FleckLog.Error("Exception string: \n" + e.ToString());
// Wait until key is pressed
Console.ReadLine();
// Close application
System.Environment.Exit(-1);
}
}
示例12: OnMessage
//Method called when a message is sent via a socket connection on the socket server
static void OnMessage(IWebSocketConnection conn,string message)
{
try
{
//Echo message
if (_echoMode)
conn.Send(message); //Echo the message back to the sender if this mode is enabled
//Debug message for message received if we have received a message
if (_debugMessages) Console.WriteLine("Message Received : " + message + ". From : " + conn.ConnectionInfo.Id.ToString());
//Check if we actually have a message - if so then carry on processing
if (conn != null && message != string.Empty)
{
//Get our request and process
var requestObject = JsonConvert.DeserializeObject<Request>(message);
if (requestObject != null)
{
DeviceCheckAndUpdate(conn, requestObject); //Check our references are up to date if a request is actually being made
UpdateMessageTime(requestObject.DeviceGuid);
//If this is an update to the devices name / account then process here as we need to keep our records up to date.
if (requestObject.Action== RequestAction.RequestId)
{
//Process the request for an Id and respond
Request idResponse = ProcessNewDeviceRequest(conn, requestObject);
conn.Send(JsonConvert.SerializeObject(idResponse)); //Single send so we can leave as its only this thread that will be sending it
}//if
else if (requestObject.Action == RequestAction.LiveCheck)
{
conn.Send(message); //Send the message back as a response to the live check + Single send so we can leave as its only this thread that will be sending it
}//else if
else
{
//We actually have a request that requires processing elsewhere so move on the data with all account devices
List<Device> connectedAccountDevices = _connectedDevices.Values.Where(d => d.AccountName == requestObject.AccountName).ToList(); //Find all devices associated with our account
string requestResponseRaw = ProcessRequest(requestObject, connectedAccountDevices); //Process our request
Response processedResponse = JsonConvert.DeserializeObject<Response>(requestResponseRaw); //Process the response
//Send out the actual data to all devices the processed request sees fit
if (processedResponse != null && processedResponse.Successful) //If the request was successful then send out to appropiate devices
{
//For each device we know we need to send out a message to do so.
foreach (var device in processedResponse.ActionDevices)
{
//Get the socket ids required from the latest connectede devices list
var devices = _connectedDevices.Where(d => d.Key == device.Id.ToString()).ToList(); //Devices that match the Ids we wish
var sockets = _connectedSockets.Where(s => (devices.Select(d => d.Value.ConnectionGuid.ToString()).ToList()).Contains(s.Key)).ToList(); //Sockets for those devices to send the data down
var messageJSON = JsonConvert.SerializeObject(processedResponse.DataToSend);
//Send the messages out
SendMessages(sockets, messageJSON);
}//foreach
}//if
}//else
}//if
}//if
}//try
catch (Exception ex)
{
//Do something with our exception
HandleException(ex, conn);
}//catch
}
示例13: OnAdd
//Method Called when a new connection is opened to the socket server
static void OnAdd(IWebSocketConnection conn)
{
try
{
//Send some data back to the client knows the connection is open and to prevent FF / Chrome issue with message sending
conn.Send("OPEN");
//Add the Socket to our list of connected sockets
_connectedSockets.TryAdd(conn.ConnectionInfo.Id.ToString(), conn);
//Debug messages
if (_debugMessages) Console.WriteLine("Socket Connection Opened : " + conn.ConnectionInfo.ClientIpAddress);
}//try
catch (Exception ex)
{
//Do something with our exception
HandleException(ex, conn);
conn.Close(); //Connection issue so close to prevent issues
}//catch
}
示例14: HandleException
//Method to handle and do something with any exceptions received
private static void HandleException(Exception ex, IWebSocketConnection conn)
{
//Do something with our exception
if(_debugMessages)
Console.WriteLine(ex.ToString());
Request exceptionRequest = new Request()
{
Action = RequestAction.RequestFailure,
Message = "There was an issue processing your request or the request was supplied in an incorrect format."
};
if (conn != null)
//conn.Send(ex.ToString()); //Issue so send the exception down the socket so we can review -- not for actual use need to log when using for real
conn.Send(JsonConvert.SerializeObject(exceptionRequest));
}
示例15: process
public void process( IWebSocketConnection socket, LinkedList<Entity> entList, NormalWorld world )
{
switch (type)
{
case "entityRequest":
foreach( Entity e in entList ) {
if( e.ID == int.Parse(args["Id"]))
{
StatusMessage toSend = new StatusMessage(e._char);
socket.Send(toSend.getJsonString());
}
}
return;
case "moveRoute":
Entity toMove = null;
foreach (Entity e in entList)
{
if (e.ID == int.Parse(args["Id"]))
{
toMove = e;
}
}
String[] coordsList = args["moveList"].Split(',');
Area[] route = new Area[coordsList.Length];
int i = 0;
foreach (String s in coordsList)
{
String[] coordsPair = s.Split(':');
route[i] = world.GetArea(int.Parse(coordsPair[0]), int.Parse(coordsPair[1]));
i++;
}
MoveLoop moveLoop = new MoveLoop(toMove, route, world);
toMove.CurObjective = moveLoop;
return;
}
}