WebSocket NodeJS

API WebSocket là một công nghệ tiên tiến cho phép mở phiên giao tiếp tương tác hai chiều giữa trình duyệt của người dùng và máy chủ. Với API này, bạn có thể gửi tin nhắn đến máy chủ và nhận phản hồi theo sự kiện mà không cần phải thăm dò ý kiến ​​​​của máy chủ để trả lời

Ghi chú. Mặc dù kết nối WebSocket có chức năng hơi giống với ổ cắm kiểu Unix tiêu chuẩn, nhưng chúng không liên quan

giao diện

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
8

Giao diện chính để kết nối với máy chủ WebSocket, sau đó gửi và nhận dữ liệu trên kết nối

WebSockets cho phép bạn gửi và nhận dữ liệu qua mạng mà không cần phải sử dụng giao thức HTTP truyền thống. Sử dụng WebSockets, bạn có thể xây dựng một ứng dụng thời gian thực. Ví dụ: bạn có thể gửi tin nhắn cho người dùng khác mà không phải làm mới trang để xem tin nhắn mới

Chúng tôi sẽ sử dụng thư viện

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
9. Nó là một nút. js cho phép bạn tạo các máy chủ và máy khách WebSockets

điều kiện tiên quyết

Trước khi bạn bắt đầu, hãy chắc chắn rằng bạn có Node. js đã cài đặt

  • Tải xuống nút. js

Cài đặt

Để cài đặt thư viện

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
9, bạn cần chạy lệnh sau

npm install ws

Tiếp theo, tạo một tệp mới có tên là

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
1 và mở nó trong trình soạn thảo văn bản yêu thích của bạn

Tạo máy chủ WebSocket

Trong tệp

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
1, tạo đoạn mã sau

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});

Tóm tắt mã

  • const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    0. Nhập mô-đun
    const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    9
  • const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    2. Tạo máy chủ WebSocket mới trên cổng 8081
  • const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    3. Khi một máy khách mới kết nối với máy chủ, sự kiện
    const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    4 được phát ra
  • const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    5. Tạo một khoảng thời gian mới gửi tin nhắn cho khách hàng mỗi giây
  • const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    6. Gửi tin nhắn cho khách hàng
  • const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    7. Khi máy khách ngắt kết nối, sự kiện
    const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    8 được phát ra
  • const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    9. Khi xảy ra lỗi, sự kiện
    const WebSocket = require('ws')
    
    const wss = new WebSocket.Server({ port: 8081 })
    
    wss.on('connection', function connection(ws) {
        console.log('Client connected')
        const interval = setInterval(() => {
            ws.send('hello world')
        }, 1000)
        ws.on("close", () => {
            console.log("Client disconnected");
        });
        ws.onerror = function () {
            console.log("Some Error occurred");
        }
    });
    
    10 được phát ra

Bằng cách đó, chúng tôi sẽ mô phỏng một ứng dụng phát trực tuyến trong đó máy chủ gửi tin nhắn đến máy khách mỗi giây

Sau đó để khởi động máy chủ, hãy chạy lệnh sau

🤩 Nhà tài trợ tuyệt vời của chúng tôi 👇

WebSocket NodeJS
Xem trang web

DigitalOcean cung cấp giải pháp lưu trữ đám mây đơn giản và đáng tin cậy cho phép các nhà phát triển nhanh chóng thiết lập và chạy trang web hoặc ứng dụng của họ

WebSocket NodeJS
Xem trang web

Bảng công việc chính thức của Laravel. Tìm các nhà phát triển Laravel giỏi nhất và tài năng nhất bằng cách đăng công việc của bạn trên bảng việc làm chính thức của Laravel

WebSocket NodeJS
Xem trang web

Tìm hiểu cách viết mã chuỗi khối của riêng bạn và tạo tiền điện tử của riêng bạn với nền tảng đào tạo trực tuyến thú vị và tương tác CoinCap. Tìm hiểu thêm về chương trình tài trợ DevDojo và xem biểu trưng của bạn tại đây để đưa thương hiệu của bạn đến với hàng nghìn nhà phát triển.

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
1

Tiếp theo, để máy chủ chạy và mở một cửa sổ đầu cuối mới, nơi chúng tôi sẽ chuẩn bị ứng dụng khách của mình

Tạo ứng dụng khách WebSocket

Trong một tệp mới có tên là tệp

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
11, hãy thêm đoạn mã sau

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
4

Đoạn mã trên tạo một máy khách WebSocket mới và kết nối với máy chủ trên cổng 8081

Khi nhận được tin nhắn từ máy chủ, sự kiện

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
12 được phát ra

Để kiểm tra máy khách, hãy chạy lệnh sau

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
6

Bạn sẽ thấy đầu ra sau

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8081 })

wss.on('connection', function connection(ws) {
    console.log('Client connected')
    const interval = setInterval(() => {
        ws.send('hello world')
    }, 1000)
    ws.on("close", () => {
        console.log("Client disconnected");
    });
    ws.onerror = function () {
        console.log("Some Error occurred");
    }
});
7

Ví dụ

WebSocket NodeJS

Phần kết luận

Đây là một ví dụ đơn giản về cách sử dụng WebSockets với Node. js

Nếu bạn muốn tìm hiểu thêm về WebSockets, hãy xem tài liệu chính thức

Nếu bạn muốn xem cách WebSockets hoạt động với Laravel, hãy xem hướng dẫn sau

Laravel WebSockets

Để đọc thêm, tôi cũng có thể khuyên bạn nên xem hướng dẫn sau về sự khác biệt giữa SSE và WebSockets là gì

WebSocket trong Nodejs là gì?

Web Socket là giao thức cung cấp giao tiếp song công (đa chiều) i. e cho phép liên lạc đồng thời theo cả hai hướng . Đây là một công nghệ web hiện đại, trong đó có một kết nối liên tục giữa trình duyệt của người dùng (máy khách) và máy chủ.

Nodejs có hỗ trợ WebSockets không?

Nút. js có thể duy trì đồng thời hàng trăm kết nối WebSockets . WebSockets trên máy chủ có thể trở nên phức tạp khi quá trình nâng cấp kết nối từ HTTP lên WebSockets yêu cầu xử lý. Đây là lý do tại sao các nhà phát triển thường sử dụng thư viện để quản lý việc này cho họ.

Làm cách nào để triển khai WebSocket trong nodejs?

Tất cả những gì chúng ta cần làm là gọi Đối tượng WebSocket bằng URI làm tham số . const webSocket = new WebSocket('ws. //máy chủ cục bộ. 443/'); . Vậy là xong, bây giờ chúng ta có thể nhận dữ liệu từ máy chủ WebSocket.

WebSocket có nhanh hơn API REST không?

Thời gian phản ứng nhanh . WebSockets allow for a higher amount of efficiency compared to REST because they do not require the HTTP request/response overhead for each message sent and received.