§2023-08-09
-
Integrating Vue.js with Socket.io@reintech.io July 29, 202
-
試作機器: hc4Lunar ubuntu 23.04
- it seems not not work as instruced?
- install npm, node and vue/cli
$ sudo apt install nodejs npm
$ sudo npm install -g @vue/cli
$ which node npm vue
/usr/bin/node
/usr/bin/npm
/usr/local/bin/vue
$ node -version
node: bad option: -version
$ node --version
v18.13.0
$ npm --version
9.2.0
$ vue --version
@vue/cli 5.0.8
- Setting up the Vue.js Project
$ pwd
/home/alexlai/vue-proj
$ vue create vue-socketio-chat
Vue CLI v5.0.8
? Please pick a preset: (Use arrow keys)
❯ Default ([Vue 3] babel, eslint) <-- I selecte this one
Default ([Vue 2] babel, eslint)
Manually select features
...
🎉 Successfully created project vue-socketio-chat.
👉 Get started with the following commands:
$ cd vue-socketio-chat
$ npm run serve
$ cd vue-socketio-chat
alexlai@hc4Lunar:~/vue-proj/vue-socketio-chat$ tree -L 1
.
├── babel.config.js
├── jsconfig.json
├── node_modules
├── package.json
├── package-lock.json
├── public
├── README.md
├── src
└── vue.config.js
4 directories, 6 files
- Next, install the required dependencies:
$ pwd
/home/alexlai/vue-proj/vue-socketio-chat
$ npm install vue-socket.io socket.io socket.io-client
¶Creating the Chat Application
Now that we have our Vue.js project set up, let's create a simple chat application. We'll start by setting up the server-side code using Node.js and Socket.io.
- Setting up the Server
Create a new file named server.js in the root directory of your project and add the following code:
` src/server.js
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('User connected');
socket.on('disconnect', () => {
console.log('User disconnected');
});
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('Listening on *:3000');
});