2

I'm making a vue 3 app, I'm starting with a web connection test visiting the official web guide, but I don't reach the goal to test it through the socket-client.io package. How do I do this?. This is what I've done about it, I need to make a socket to a external website (There is no need to have a backend part to make this possible or a sample):

  • I put the Socket.ts at the root of the project.

     import { reactive } from 'vue'
     import { io } from 'socket.io-client'
    
     export const state = reactive({
       connected: false
     })
    
     export const socket = io('https://www.google.com')
    
     socket.on('connect', () => {
       state.connected = true
     })
    
     socket.on('disconnect', () => {
       state.connected = false
     })
    
  • then I'm using it in my component:

<script setup lang="ts">
import { state } from '../Socket'
import { socket } from '../Socket'
const connected = computed(() => {
  return state.connected
})
onMounted(async () => {
console.log
  socket.connect()
})
</script>
<template>
<p> {{ connected}} </p>
</template>
tsiPlus
  • 63
  • 9
  • there could be a lot of reasons including the backend part. i would suggest to prepare a sample working project and share it for example on replit.com – Alexander Nenashev Jul 25 '23 at 08:43

1 Answers1

1

The export const socket = io('https://www.google.com') part seems... improbable.
See socket.io Troubleshooting: Problem: the socket is not able to connect

You are trying to reach a plain WebSocket server

If you are testing out socket.io, I would suggest setting up a simple socket.io server locally, and then connecting to it from your Vue app.
npm install express socket.io, and, in a new folder, create a server.js file:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

io.on('connection', (socket) => {
  console.log('New client connected');
  socket.on('disconnect', () => {
    console.log('Client disconnected');
  });
});

server.listen(4001, () => console.log(`Listening on port 4001`));

Then you can change the address in your Vue app to http://localhost:4001:

import { reactive } from 'vue'
import { io } from 'socket.io-client'

export const state = reactive({
  connected: false
})

export const socket = io('http://localhost:4001')

socket.on('connect', () => {
  state.connected = true
})

socket.on('disconnect', () => {
  state.connected = false
})

Now you should see a log message in the server console when your Vue app connects to the server.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250