The article directories

        • See the effect
        • above
        • Client code
        • Server code
        • Service runs
          • Install the node
          • Initialization package. Js
          • Install nodemon
          • Install socket. IO
        • Thank you for reading

See the effect

Always said I like to keep in suspense, this time to see the effect:



Chat interface (like you can draw a more realistic page)

above

Say the first why write this stuff, not recently wrote NodeJS combing knowledge points, but I found that the process of combing really bored to death, although already fast half combed, just haven’t release, this is not important, important is not to do something really boring, so today I do the process record to you see, If you like it, you can have it. The function can be chat, can display user-defined nickname, and display the sending time PS: This function can save a lot of code if we use WebStorm to create a new Express app project, but we choose to implement it native here, because we cannot always rely on the framework or wheels built by others to write code. Although we advocate not to duplicate wheels, But if every programmer thought like that, the industry would have no wheels.

Client code

<! DOCTYPEhtml>
<html>

<head>
    <meta charset="utf-8">
    <title>http_demo</title>
    <script src="/socket.io/socket.io.js"></script>
</head>

<body>
    <h1>
        WelCome to CSDN of clearlove
    </h1>
    <p>
        If you like my article, you can follow my blog
    </p>
    <p>Public chat screen</p>
    <div id="infos">

    </div>
    <input style="margin-top: 5vh; width: 100px; height: 40px; border: 1px solid #ffffff; border-radius: 4px; color: #000000; padding-left: 10px" type="text" id="nick" value="" placeholder="Nickname" />
    <input type="text" id="send_info" value="" placeholder="Please enter what you want to say." />
    <button type="button" id="btn">send</button>
</body>
<script>
    // Create an IO object
    var socket = io();
    // When the user clicks "send", the user will send the nickname and the message content directly. If there is no nickname, it will display the anonymity and determine whether there is a value
    document.getElementById("btn").onclick = function () {
        if(document.getElementById("send_info").value){
            socket.emit("link_to_server".document.getElementById("send_info").value, document.getElementById("nick").value ? document.getElementById("nick").value : 'anonymous')}else{
            alert('Send content cannot be empty')}}// Display the received information, create a new element, append to div
    socket.on('link_to_client'.function (msg) {
        var h6 = document.createElement('h6');
        h6.innerText = `${msg}`;
        document.getElementById('infos').append(h6)
    })
</script>
<style>
    body {
        background: #307ac6;
        text-align: center;
        color: aliceblue;
        margin: 0% 10%
    }

    p {
        font-size: 2rem
    }

    input {
        margin-top: 5vh;
        width: 200px;
        height: 40px;
        border: 1px solid #ffffff;
        border-radius: 4px;
        color: # 000000;
        padding-left: 10px;
    }

    button {
        border: none;
        background: #ffffff;
        border-radius: 4px;
        width: 90px;
        height: 42px;
        color: # 000000;
    }

    #infos {
        margin-left: 25vw;
        width: 400px;
        height: 500px;
        overflow: scroll;
        border: none;
        background: #ffffff;
        color: # 000000;
    }
</style>

</html>
Copy the code

Server code

/ * * *@author clearlove
 * @aim Test connection to a socket. IO communication broadcast */
/ / introduction of the fs
var fs = require('fs')
/ / incoming HTTP
var http = require('http')
var date = new Date(a)/ * * *@FormDate Formatting time@param {*} Date Current time */
function FormDate(date) {
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}  ${date.getHours()}:${date.getMinutes()}`
}
/** * Set up a server */
var server = http.createServer(function (res, res) {
    if(res.url ! = ='/favicon.ico') {
        res.writeHead(200, { "Content-type": "text/html" })
        const myreadstream = fs.createReadStream(__dirname + '/views/http_demo.html'.'utf-8')
        myreadstream.pipe(res)
    }
})
IO = require('socket.io'); IO = require('socket.io')
var io = require('socket.io')(server);

io.on("connection".function (socket) {
    // The IP address of the peer can be displayed or not displayed, or the IP address can be filtered
    var clientIp = socket.request.connection.remoteAddress
    console.info("A socket connection was successful")
    socket.on("link_to_server".function (msg, nick) {
        // Use IO to send
        io.emit('link_to_client'.`${nick} : ${msg}  ${FormDate(date)}`)
    })
})
server.listen(5000.'0.0.0.0');
console.info("server is running...")
Copy the code

Service runs

  • Hide the IP for security

, of course, I use some of the above may be ‘native’, directly create elements of what, because I didn’t introduce a framework such as jquery, introduction is quite simple, but does not affect us to achieve the basic chat functionality, there may be some you don’t understand, or you all understand Including why the startup is not a node + but nodemon + file name, file name, what is the difference between what’s good, it doesn’t matter, at the back of the article I will introduce the use of all the knowledge points, specific how to use, how to come out, why do you write, step by step how to achieve the effect of this, I will update the following articles, why write this at this time? The reason is that I want more people to know that NodeJS is a fun language in and of itself, and there’s a lot you can do with it. If you like NodeJS after reading my article, that’s my goal. After all, I still think NodeJS is a very powerful language, and I hope more people use it.

If you want to play with emmmmm, you can install Node, initialize a package.json file locally, and install Nodemon and socket. IO

Install the node

Download the Next step of Node and you’re done

Initialization package. Js

npm init

  • Enter the name version number and press Enter
Install nodemon

npm install -g nodemon –save-dev

Install socket. IO

npm install socket.io –save-dev

It might be a little easier to write, but the reason is I’m going to go into more detail, so I’m not going to write it here…

Thank you for reading