How to Build a WebSocket Server for Remote Control via WeChat Mini Program

This tutorial walks through setting up a Node.js WebSocket server, creating a PC client and a WeChat Mini Program client, and enabling bidirectional communication so the mini program can remotely control a projector screen.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
How to Build a WebSocket Server for Remote Control via WeChat Mini Program

Background

The author wanted to control a projector screen remotely using a WeChat Mini Program and realized that WebSocket, although not new, can bridge the Mini Program and a PC to achieve this.

Development Process

1. Build the WebSocket Server

Install Node.js from the official website and verify the installation with node -v. Then install the WebSocket module: npm install ws Create app.js with the following content and place it in the project directory:

//app.js
var conns = {};
var wss = require('ws').Server;
var server = new wss({
  host: "127.0.0.1",
  port: 9999
});
server.on('connection', function(ws) {
  ws.on('message', function(message) {
    console.log(message);
    var msg = JSON.parse(message);
    if (msg.id) {
      conns[msg.id] = msg['info'];
      conns[msg.id]['conn'] = ws;
      console.log(conns[msg.id]['name'] + ' - 已连接');
    }
    if (msg.fromId && msg.toId && msg.data) {
      var temp = {
        'name': conns[msg.fromId]['name'],
        'msg': msg.data
      };
      conns[msg.toId]['conn'].send(JSON.stringify(temp));
    }
  });
});
console.log('WebSocket server running...');

Start the server with:

node app.js

2. PC Client (My Computer)

Use the following JavaScript to connect to the server, send client information, and handle messages:

// Create WebSocket connection
var ws = new WebSocket("ws://127.0.0.1:9999/");
ws.onopen = function() {
  console.log("Opened");
  var obj = { id: 1, info: { name: '我的电脑' } };
  ws.send(JSON.stringify(obj));
};
ws.onmessage = function(res) {
  var temp = JSON.parse(res.data);
  if (temp.msg == $('.metro li').length) {
    $('.close').click();
  } else {
    $('.metro li:eq(' + temp.msg + ')').click();
  }
  console.log('收到[' + temp.name + ']发来的消息:' + temp.msg);
};
ws.onclose = function() { console.log("Closed"); };
ws.onerror = function(err) { console.log("Error: "); console.log(err); };

3. WeChat Mini Program Client

In the Mini Program, establish the WebSocket connection and bind button events to send control commands:

var that = this;
wx.connectSocket({ url: 'ws://127.0.0.1:9999/' });
wx.onSocketOpen(function(res) {
  console.log("Opened");
  var obj = { id: 2, info: { name: '微信小程序' } };
  wx.sendSocketMessage({ data: JSON.stringify(obj) });
  that.remoteCtrl = function(e) {
    wx.sendSocketMessage({
      data: JSON.stringify({ fromId: 2, toId: 1, data: e.currentTarget.id })
    });
  };
});
wx.onSocketMessage(function(res) {
  var temp = JSON.parse(res.data);
  console.log('收到[' + temp.name + ']发来的消息:' + temp.msg);
});
wx.onSocketClose(function(res) { console.log("Closed"); });
wx.onSocketError(function(res) { console.log("Error: "); console.log(err); });

4. Communication Between PC and Mini Program

With the server and both clients running, messages sent from the Mini Program are routed to the PC client and vice‑versa, enabling the Mini Program to remotely control the PC (e.g., switching projector screens).

Summary

The simple demo demonstrates how WebSocket can be used for remote control scenarios. Beyond this, the same technique can power chat rooms, online games, real‑time bullet comments, and many other interactive applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptNode.jsWeChat Mini ProgramWebSocketremote control
Tencent IMWeb Frontend Team
Written by

Tencent IMWeb Frontend Team

IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.