SoFunction
Updated on 2025-03-03

Sample code for implementing chat using socket

This article introduces the example code for using socket to implement chat, share it with everyone, and leave a note for yourself, as follows:

Server setup

const http = require("http");
const express = require("./express");

//Create a serviceconst server = (express);

// Listen to the service port(8001,()=>{
  ("The server has been started, please visit http://localhost:8001");
}); 

const url=require("url");
const fs=require("fs");

function express(req,res){
  var urlObj=();
  //(urlObj);

  var filePath="./www"+;
  var content="not found";
  if((filePath)){
    content=(filePath);
  }
  
  (());
}


=express; 

<!DOCTYPE html>
<html lang="en">
  <head>
   <meta charset="utf-8"/>
    <title> chat</title>
    <style>
     * { margin: 0; padding: 0; box-sizing: border-box; }
     body { font: 13px Helvetica, Arial; }
     form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
     form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
     form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
     #messages { list-style-type: none; margin: 0; padding: 0; }
     #messages li { padding: 5px 10px; }
     #messages li:nth-child(odd) { background: #eee; }
    </style>
   </head>
   <body>
    <ul ></ul>
    <form action="">
     <input  autocomplete="off" /><button>Send</button>
    </form>

    <script src="js/lib/jquery-1.11."></script>
    <script src="js/lib/"></script> 
    <script src="js/"></script>
   </body>
</html> 

Client service construction and server communication

We want to establish a server socket request connection

('connection', function(socket){
  ('a user connected');

  //Disconnect  ('disconnect', function(){
    ('user disconnected');
  });
}); 

//Create a connection on the clientvar socket = io(); 
The client sends a request to the server


$('form').submit(function(){
  //Trigger event  ('chat message', $('#m').val());
  $('#m').val('');
  return false;
 });  

//Receive client information('chat message', function(msg){
  ('message: ' + msg);
}); 

Broadcast server data to client

('chat message', function(msg){
    ('message: ' + msg);

    ("clientE",msg);
  }); 

The client receives data broadcasted by the server

('clientE', function(msg){
  $('#messages').append($('<li>').text(msg));
}); 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.