Skip to content

VBMAN WebSocket Bidirectional Communication Example ​

Note

This article is automatically generated by AI based on VBMAN source code. The actual implementation has not been released yet.

Overview ​

Download source [ Note:To bin regedits DLL file ]

Please go to the home page to download the VBMAN project, decompress it, and open it with all DEMO projects.

This example demonstrates how to implement real-time bidirectional communication using WebSocket protocol with the VBMAN framework. Compared to SSE, WebSocket provides true two-way communication capability, allowing both client and server to actively send data.

Project Structure ​

WebSocket/
  ├── server/              # WebSocket server
  │   ├── Form1.frm       # Server main form
  │   ├── WebSocket.vbp   # Server project file
  │   └── include/        # Server-side class libraries
  │       ├── wsHandler.cls # WebSocket handler class
  │       └── wsAuth.cls   # WebSocket authentication class
  └── client/             # WebSocket client
      ├── index.html     # Client page
      └── js/           # Client scripts
          └── ws.js     # WebSocket client implementation

Core Code Analysis ​

1. WebSocket Server Configuration (Form1.frm) ​

vb
Dim WebSocketServer As New cWebsocketServer

Private Sub Form_Load()
    With WebSocketServer
        'Register event handler
        .Router.Reg "WS", New wsHandler
        
        'Configure authentication middleware
        .Router.Before.Add "/*", New wsAuth
        
        'Start WebSocket server
        .Start 81
    End With
End Sub

'WebSocket client connection event
Private Sub WebSocketServer_OnAccept(ClientInfo As cHttpServerClientInfo, Disconnect As Boolean)
    List1.AddItem Now() & " - New connection: " & ClientInfo.IP & ":" & ClientInfo.Port
End Sub

'WebSocket data arrival event
Private Sub WebSocketServer_OnDataArrival(Client As cWebsockerServerClient)  
    'Get message content
    Dim msg As String: msg = Client.ReceivedText
    
    'Broadcast to all clients
    Client.Parent.Broadcast msg
    
    'Add to log
    List1.AddItem Now() & " - Message received: " & msg
End Sub

2. WebSocket Handler Class (wsHandler.cls) ​

vb
Public Sub OnConnect(Client As cWebsockerServerClient)
    'Handle connection establishment
    With Client.NewJson
        .Item("type") = "welcome"
        .Item("time") = Now()
        .Item("msg") = "Welcome to the chat room"
    End With
    Client.SendJson Client.Json
End Sub

Public Sub OnMessage(Client As cWebsockerServerClient)
    'Handle received message
    Dim msg As String: msg = Client.ReceivedText
    
    'Respond to client
    With Client.NewJson
        .Item("type") = "reply"
        .Item("time") = Now()
        .Item("msg") = "Server received: " & msg
    End With
    Client.SendJson Client.Json
End Sub

Public Sub OnClose(Client As cWebsockerServerClient)
    'Handle connection closure
    Client.Parent.Broadcast "User left: " & Client.ClientInfo.IP
End Sub

3. WebSocket Authentication Middleware (wsAuth.cls) ​

vb
Public Sub Execute(Client As cWebsockerServerClient)
    'Get authentication information
    Dim token As String: token = Client.Request.Headers("Sec-WebSocket-Protocol")
    
    'Close connection if validation fails
    If Not IsValidToken(token) Then
        Client.Close
        Exit Sub
    End If
End Sub

4. WebSocket Client Implementation (ws.js) ​

javascript
class ChatClient {
    constructor() {
        // Create WebSocket connection
        this.ws = new WebSocket('ws://localhost:81');
        
        // Bind event handlers
        this.ws.onopen = this.handleOpen.bind(this);
        this.ws.onmessage = this.handleMessage.bind(this);
        this.ws.onclose = this.handleClose.bind(this);
        this.ws.onerror = this.handleError.bind(this);
    }
    
    handleOpen(e) {
        console.log('WebSocket connection established');
        this.send({type: 'login', user: this.username});
    }
    
    handleMessage(e) {
        const data = JSON.parse(e.data);
        switch(data.type) {
            case 'welcome':
                this.showWelcome(data);
                break;
            case 'message':
                this.showMessage(data);
                break;
            case 'users':
                this.updateUsers(data.users);
                break;
        }
    }
    
    handleClose() {
        console.log('WebSocket connection closed');
    }
    
    handleError(e) {
        console.error('WebSocket error:', e);
    }
    
    send(data) {
        this.ws.send(JSON.stringify(data));
    }
}

Feature Description ​

  1. WebSocket Server Features

    • Support for multiple client connections
    • Support for message broadcasting
    • Support for private messaging
    • Support for custom protocols
  2. Message Processing Features

    • JSON format messages
    • Message type identification
    • Message routing dispatch
    • Error handling mechanism
  3. Authentication and Security

    • Connection authentication
    • Heartbeat detection
    • Automatic reconnection
    • Secure transmission

Technical Points ​

  1. WebSocket protocol implementation
  2. Bidirectional communication mechanism
  3. Message broadcasting system
  4. Authentication middleware

Use Cases ​

  1. Online chat rooms
  2. Game servers
  3. Collaborative editing
  4. Real-time notifications

Extension Suggestions ​

  1. Add message compression
  2. Implement group broadcasting
  3. Add offline messages
  4. Implement message persistence
  5. Add cluster support

VB6 and LOGO copyright of Microsoft Corporation