vb.net的ashx来作的WebSocketRequest 请求聊天代码,现在网上关于vb.net的代码越来越少了,而对于websocket的代码更少。
首页要定义一个公共用户组,然后将每一个请求的全部放到数组中挂起,用户有消息了再进行转发。
Public ChatList As New Dictionary(Of String, Net.WebSockets.WebSocket) '当前在线的用户
-
<%@ WebHandler Language="VB" Class="Chat" %>
-
-
Imports System.Text.Encoding '引用文本编码
-
-
Imports System.Net.WebSockets
-
Public Class Chat : Implements IHttpHandler
-
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
-
-
-
-
-
Public Sub ProcessRequest(ByVal Context As HttpContext) Implements IHttpHandler.ProcessRequest
-
If Context.IsWebSocketRequest = False Then Context.Response.Write("请求类型错误") : Context.Response.End()
-
Context.AcceptWebSocketRequest(AddressOf SocketHandler) '接到一个请求
-
-
-
Private Async Function SocketHandler(Context As WebSockets.AspNetWebSocketContext) As Tasks.Task
-
-
Dim WS As WebSocket = Context.WebSocket, ID As String = GetRequest("ID", 8)
-
If ChatList.ContainsKey(ID) = True Then '检查是否在线包含
-
-
-
-
-
-
Dim Buffer As New ArraySegment(Of Byte)(New Byte(2048) {}), Result As WebSocketReceiveResult
-
-
Select Case WS.State'连接状态
-
Case WebSocketState.None, WebSocketState.Connecting '正在连接不处理
-
Case WebSocketState.Open '已连接
-
Result = Await WS.ReceiveAsync(Buffer, CancellationToken.None)
-
If Result.EndOfMessage = True AndAlso Result.Count > 0 Then
-
Message(ID, Buffer.Array, Result.Count)
-
-
Case WebSocketState.CloseSent, WebSocketState.CloseReceived, WebSocketState.Closed, WebSocketState.Aborted '断开连接
-
-
-
-
-
-
-
SoftLog(ex.ToString, "Chat.txt") '记录系统错误
-
-
-
-
Sub Message(UserID As String, Buffer() As Byte, Count As Integer)
-
-
Dim RStr As String = Encoding.UTF8.GetString(Buffer, 0, Count), Json As Object = JsonConvert.DeserializeObject(RStr)
-
If Json("MsgType") = False Then Return
-
-
-
-
If UserID <> "1" AndAlso ChatList.ContainsKey("1") = True Then
-
RStr = "成功:" & ChatList.Count
-
ChatList("1").SendAsync(New ArraySegment(Of Byte)(Encoding.UTF8.GetBytes(RStr)), WebSocketMessageType.Text, True, CancellationToken.None)
-
-
-
-
-
-
ElseIf UserID <> "2" AndAlso ChatList.ContainsKey("2") = True Then
-
RStr = "成功:" & ChatList.Count
-
ChatList("2").SendAsync(New ArraySegment(Of Byte)(Encoding.UTF8.GetBytes(RStr)), WebSocketMessageType.Text, True, CancellationToken.None)
-
ElseIf UserID <> "3" AndAlso ChatList.ContainsKey("3") = True Then
-
RStr = "成功:" & ChatList.Count
-
ChatList("3").SendAsync(New ArraySegment(Of Byte)(Encoding.UTF8.GetBytes(RStr)), WebSocketMessageType.Text, True, CancellationToken.None)
-
-
-
-
RStr = "当前在线:" & ChatList.Count
-
ChatList(UserID).SendAsync(New ArraySegment(Of Byte)(Encoding.UTF8.GetBytes(RStr)), WebSocketMessageType.Text, True, CancellationToken.None)
-
-
-
-
-
-
-
-
ChatList(UserID).Abort() '断开连接
-
ChatList.Remove(UserID) '用户下线
-
SoftLog(ex.ToString) '记录系统错误
-
-
-
这是我作的效果,包括文字、语音、视频、红包类聊天