WeChat applet|Make a chat system based on applet + C#

This article is mainly based on the small program + C# to make a chat system using WebSocket, basically realizing the chat function between the small program and the server. The customer service function that comes with the mini program can only be bound to WeChat and communicate one-on-one, and the budget for accessing the mature instant messaging on the market is slightly insufficient, so you can simply develop one yourself that can also handle simple business scenarios.

Implementation process

1. Server

1.1. Project creation

  1. Open Visual Studio and select Create New Project on the right.

  1. Enter winform in the search box, select the windows form application, fill in the corresponding save path and click Next, as shown in the figure below after the creation is successful.


1.2. Design interface

  1. Drag and drop the lable text tag from the toolbox to modify its text property to fill the title.

  1. Drag and drop the textbox control onto the form to input the monitored port number and sent text information, etc.

  1. Next, drag in the button control and the listview control in order to realize the button and message panel styles.

1.3. Realization of server functions

  1. Implement the websocket server startup function.

Double-click the button button to generate a corresponding button event. In the event code, first check whether the value entered in the port number text box is correct.

 int port = 9000;
 if (textBox_port.Text == string.Empty)
   {
       MessageBox.Show("Please fill in the port", "system hint", MessageBoxButtons.OK, MessageBoxIcon.Information);
       return;
   }
   try
   {
       port = Convert.ToInt32(textBox_port.Text.Trim());
   }
   catch
   {
       MessageBox.Show("Please fill in the correct port", "system hint", MessageBoxButtons.OK, MessageBoxIcon.Information);
       return;
   }

After clicking, the button is disabled to prevent the user from opening the server while repeatedly clicking.

try
{
         var result = _server.Open(port, "DIS");
         if (result)
         {
             this.toolStripLabel_event.Text = "Start successfully";
             this.toolStripLabel_event.ForeColor = Color.Green;
             this.toolStripLabel1.Text = "Listening port:" + port.ToString();
             WSocketServer._Logger.Info("The server started successfully");
         }
         else
         {
             this.toolStripLabel_event.Text = "failed to activate";
             this.toolStripLabel_event.ForeColor = Color.Red;
             this.toolStripLabel1.Text = "Listening port:" + port.ToString();
             button_StartListen.Enabled = true;
             button_StopListen.Enabled = false;
             button_Send.Enabled = false;
             WSocketServer._Logger.Error("Server failed to start");
         }
     }
     catch (Exception ex)
     {
         WSocketServer._Logger.Error("Server failed to start:"+ ex.ToString());
     }

To realize the method of opening the server, here you need to configure various information of the websocket.

this.WebSocket = new WebSocketServer();
var serverConfig = new ServerConfig
{
    Name = serverName,
    MaxConnectionNumber = 10000, //The maximum number of client connections allowed, the default is 100.
    Mode = SocketMode.Tcp,
    Port = port, //The port the server listens on.
    ClearIdleSession = false,   //true or false, whether to clear idle sessions, the default is false.
    ClearIdleSessionInterval = 120,//The interval for clearing idle sessions, the default is 120, and the unit is second.
    ListenBacklog = 10,
    ReceiveBufferSize = 64 * 1024, //The buffer size for receiving data, the default is 2048.
    SendBufferSize = 64 * 1024,   //The buffer size of the data sent by the user, the default is 2048.
    KeepAliveInterval = 1,     //The interval for sending keep alive messages. The unit is seconds.
    KeepAliveTime = 60,    //The interval between keep alive retries. The unit is seconds.
    SyncSend = false
};
SocketServerFactory socketServerFactory = null;
//Open wss to use the certificate
if (isUseCertificate)
{
    serverConfig.Security = serverSecurity;
    serverConfig.Certificate = new SuperSocket.SocketBase.Config.CertificateConfig
    {
        StoreName = serverStoreName,
        StoreLocation = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
        Thumbprint = serverThumbprint
    };
    socketServerFactory = new SocketServerFactory();
}
  1. Realize the message sending function.

Double-click the send button to get the client network node number to send data to and fill the sent text into the message panel.

 //client network node number
string remoteEndPointStr = session.RemoteEndPoint.ToString();
if (remoteEndPointStr == s)
{
    try
    {
        ReceiveData sendData = new ReceiveData();
        //send data
        sendData.User = "guest";
        sendData.Type = "msg"; 
        sendData.Msg = textBox_msg.Text.Trim();
        sendData.SendTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        _server.SendMessage(session, JsonConvert.SerializeObject(sendData));
        this.BeginInvoke(addListView, "guest", JsonConvert.SerializeObject(sendData));
        MessageBox.Show("Sent successfully", "system hint", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return;
    }
    catch (Exception ex)
    {
        WSocketServer._Logger.Error(ex.ToString());
        MessageBox.Show(ex.ToString(), "system hint", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return;
    }
}
  1. Realize the message monitoring function, receive data from the client and display it.

 /// <summary>
 /// received data
 /// </summary>
 /// <param name="session">session</param>
 /// <param name="rData">value</param>
 private void Server_MessageReceived(SuperWebSocket.WebSocketSession session, string rData)
 {
     //IP address
     string ipAddress_Receive = session.RemoteEndPoint.ToString();
     if (rData.Equals(""))
     {
         //Empty data does not return server information
         return;
     }
     try
     {
         //Received something sent by the client link
         ReceiveData receiveData = JsonConvert.DeserializeObject<ReceiveData>(rData);
         receiveData.SendTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
         switch (receiveData.Type)
         {
             case "HeartBeat":
                 //heartbeat
                 //Send client connection success message
                 //_server.SendMessage(session, "HeartBeat");
                 break;
             default:
                 //Return user sent data
                 _server.SendMessage(session, JsonConvert.SerializeObject(receiveData));
                 break;
         }
     }
     catch
     {
         WSocketServer._Logger.Error("Receive abnormal data:" + rData);
         //Error data does not return server information
         return;
     }
     if (MsgFalg)
     {
         //The server shows that the client sends and accepts information
         this.BeginInvoke(addListView, ipAddress_Receive, rData);
     }
 }

2. Small programs

2.1. Small program creation

  1. access Micro-channel public platform , click Account Registration.

  1. Select the applet, and fill in the required information in the form to register.


  1. Select Development Settings in Development Management, and copy AppID and AppSecret for storage.

  1. Download and install the WeChat web developer tools and create a new project, fill in the AppId copied in the above picture.


2.2. Page design

  1. The page judges where the message will be displayed according to the sender, and also needs to provide a text box and button to realize the sending function.

<view class="cu-chat" id="j_page">
  <view class="cu-item {{item.User==''?'self':''}}" wx:for="{{chatData}}">
    <view class="cu-avatar radius" style="background-image:url(../../image/cat.jpg)" wx:if="{{item.User=='guest'}}"></view>
    <view class="main">
      <view class="content shadow {{item.User==''?'bg-green':''}}">
        <text>{{item.Msg}}</text>
      </view>
    </view>
    <view class="cu-avatar radius" style="background-image:url(../../image/fm3.jpg)" wx:if="{{item.User==''}}"></view>
    <view class="date">{{item.SendTime}}</view>
  </view>
</view>
  1. Obtain the content entered by the user through the blur event of the text box.

  formMsg(e) {
    this.setData({
      content: e.detail.value.trim()
    })
  },

2.3. Message reception

  1. Create a websocket connection in the onload event of js, and listen to messages from the server at the same time. The port number can be changed to a configuration type.

    let that = this;
    socket = wx.connectSocket({
      url: 'ws://localhost:9000/',
      success: res => {
        //console.info('Connection created successfully');
      }
    });
    // console.info(socket);
    //event listener
    socket.onOpen(function () {
      //console.info('Connection opened successfully');
    });
    socket.onClose(function () {
      //console.info('Connection closed successfully');
    });
    socket.onError(function () {
      console.info('connection error');
    });
    //The server sends the listener
    socket.onMessage(function (e) {
      console.info(JSON.parse(e.data));
      var info = JSON.parse(e.data);
      that.setData({
        chatData: that.data.chatData.concat(info)
      });
      // that.setData({chatData:list});
    });
  1. In the monitoring callback, print the text sent by the server and you can see the effect as shown in the figure below.


  1. Render the data on the page according to its format, the effect is as follows.

2.4. Message sending

  1. The send button is bound to a custom function to obtain the value entered by the user in the text box, and transmit the data through the built-in function of websocket, so that the server can receive and display the data.

    wx.sendSocketMessage({
      data: info,
      success: function (res) {
      },
      fail: function (res) {
       
      }
    })

Interested partners can expand on the basis of articles, and add more practical functions such as group sending, file sending, and picture sending.

Tags: C# Windows Mini Program

Posted by Cory94bailly on Mon, 12 Dec 2022 23:02:01 +0300