I am creating a websocket chat application and I managed to relay chat messages to other browsers connected. I have a console application listening on one port.
My question is... If one person logs on to the system I want everybody to know that, how can I do that? I'm using Linq to map the DB but if the logging is ok how do I send that message, that user X has logged in?
FINALLY I was able to create a chatroom using websockets, here is the final product, thanks for the orientation!
First make sure you're sending messages as JSON (JavaScript Object Notation) as this allows structured data to be sent back and forth, and client & server can differentiate between a chat message and an instruction (eg someone new logged in). For instance on the client:
mySocket.onmessage = function(event) {
var command = JSON.parse(event.data);
if(command.type === 'message') {
var message = command.message;
// handle chat message
}
else if (command.type === 'newUser') {
var username = command.username;
// handle new user
}
};
On the server in ASP.NET C# you'd send them as:
public class ChatHandler : WebSocketHandler
{
private JavaScriptSerializer serializer = new JavaScriptSerializer();
private static WebSocketCollection chatapp = new WebSocketCollection();
public override void OnMessage(string message)
{
var m = serializer.Deserialize<Message>(message);
switch (m.Type)
{
case MessageType.NewUser:
chatapp.Broadcast(serializer.Serialize(new
{
type = "newUser",
username = m.username
}));
break;
case MessageType.Message:
chatapp.Broadcast(serializer.Serialize(new
{
type = "message",
message = m.message
}));
break;
default:
return;
}
}
}
As Hightechrider says, you'll need to keep track of a list of connected clients, that's what WebSocketCollection
class does in the code listing above.
Check out Paul Batum's WebSocket chat example on github here ( https://github.com/paulbatum/BUILD-2011-WebSocket-Chat-Samples/blob/master/BasicAspNetChat/ChatHandler.cs )
Also he did a presentation at the recent MS BUILD conference here ( http://channel9.msdn.com/Events/BUILD/BUILD2011/SAC-807T )
You would need to track the connections at the application level so you can send to all of them. But take a look at SignalR instead where a lot of the work involved with webSockets and long polling is being written for you. With SignalR you can use GetClients
to get all the clients connected to a Hub
.
使用PostgreSQL时,可以在数据库中使用NOTIFY来通知应用程序层,该应用程序层可以生成通过WebSockets发送的消息。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.