HTML5-WebSocket实现聊天室示例

2020-04-24 19:23:15易采站长站整理

在传统的网页实现聊天室的方法是通过每隔一段时间请求服务器获取相关聊天信息来实现,然而html5带来的websocket功能改变这了这种方式.由于websocket在连接服务器后允许保持连接来进行数据交互,因此服务器可以主动地向客户端发送相应的数据.对于html5的处理只需要在连接创建完成后在websocket的receive事件中处理接收的数据即可.下面通过实现一个聊天室来体验一下服务器可以主动地向客户端发的功能.

功能

一个简单的聊天室主要有以下几个功能:

1)注册

注册要处理几个事情,分别是注册完成后获取当前服务器所有用户列表,服务把当前注册成功的用户发送给其他在线的用户.

2)发信息

服务器把当前接收的消息发送给在线的其他用户

3)退出

服务器把断开的用户通知其他用户

聊天室完成的功能预览如下:

C#服务端代码

服务端的代码只需要针对几功能定义几个方法即可,分别是注册,获取其他用户和发送信息.具体

/// <summary>

/// Copyright © henryfan 2012

///Email: henryfan@msn.com

///HomePage: http://www.ikende.com

///CreateTime: 2012/12/7 21:45:25

/// </summary>

class Handler

{

public long Register(string name)

{

TcpChannel channel = MethodContext.Current.Channel;

Console.WriteLine("{0} register name:{1}", channel.EndPoint, name);

channel.Name = name;

JsonMessage msg = new JsonMessage();

User user = new User();

user.Name = name;

user.ID = channel.ClientID;

user.IP = channel.EndPoint.ToString();

channel.Tag = user;

msg.type = "register";

msg.data = user;

foreach (TcpChannel item in channel.Server.GetOnlines())

{

if (item != channel)

item.Send(msg);

}

return channel.ClientID;

}

public IList<User> List()

{

TcpChannel channel = MethodContext.Current.Channel;

IList<User> result = new List<User>();

foreach (TcpChannel item in channel.Server.GetOnlines())

{

if (item != channel)

result.Add((User)item.Tag);

}

return result;

}

public void Say(string Content)

{

TcpChannel channel = MethodContext.Current.Channel;

JsonMessage msg = new JsonMessage();

SayText st = new SayText();

st.Name = channel.Name;

st.ID = channel.ClientID;

st.Date = DateTime.Now;

st.Content = Content;

st.IP = channel.EndPoint.ToString();

msg.type = "say";