简体   繁体   English

如何配置socket.io监听客户端

[英]How to configure socket.io to listen to client side

I am new to using sockets and do not fully understand how they work.我是使用套接字的新手,并不完全了解它们的工作原理。

When i load my website I get this error I just get this error "chat.js:4563 GET http://localhost/socket.io/?EIO=3&transport=polling&t=N3Jn3vr 404 (Not Found)"当我加载我的网站时出现此错误我只是收到此错误“chat.js:4563 GET http://localhost/socket.io/?EIO=3&transport=polling&t=N3Jn3vr 404 (Not Found)”

What am I missing?我错过了什么? I am assuming I have to make the two ports work with one another somehow?我假设我必须以某种方式使这两个端口相互协作?

socket.js file: socket.js 文件:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

http.listen(3000, function(){
  console.log('listening on *:3000');
});

io.on('connection', function(socket){
  socket.on('chat.message', function(message) {
     console.log('x: ' +  message)
  })
});

chat.js file: chat.js 文件:

import io from 'socket.io-client';

const socket = io('http://localhost:80');

var app = new Vue({
    el: '#app',
    mounted() {
    },
    data: {
      message: null
    },
    methods: {
        send() {
            socket.emit('chat.message', this.message)
    }
}})

blade file:刀片文件:

@extends('dashboard.base')

@section('content')

    <div class="container-fluid">
        <div class="fade-in">
            <div class="row">
                <div class="card mx-auto text-center w-50">
                    <div  class="card-header">
                        Live Chat
                    </div>
                    <div id="app" class="card-body">
                        <input v-model="message" type="text">
                        <span class="btn btn-success" @click="send">Send</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

@endsection

@section('javascript')
    <script src="{{ mix('js/chat.js') }}"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
@endsection

As both express and socket.io are using http they will share the same port.由于 express 和 socket.io 都使用http它们将共享相同的端口。 So you should listen to socket connections on port 3000 instead of port 80.所以你应该在端口 3000 而不是端口 80 上监听套接字连接。

You could just initialize the socket object with io without the url, as it's on the same port as your express app.您可以在没有 url 的情况下使用io初始化套接字对象,因为它与您的 Express 应用程序位于同一端口上。 Socket.io will connect to the same host that serves the page Socket.io 将连接到为页面提供服务的同一台主机

const socket = io();

The getting started page here gives an overview of the same.此处的入门页面提供了相同的概述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM