如何在客户端导入 socket.io - SOCKET.IO + NODE.JS [英] How to import socket.io on client side - SOCKET.IO + NODE.JS

查看:72
本文介绍了如何在客户端导入 socket.io - SOCKET.IO + NODE.JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建一个在线游戏,但是当我尝试使用 socket.on(...);socket.emit(...)它出现了一个类似于 socket 的错误.我看过一些与此类似的帖子,并尝试了所有解决方案,但都没有奏效.我已经让 io.connect(...); 工作并且工作正常(我认为这意味着我已经正确设置了 socket.io-client).我只是不明白我做错了什么.如果您需要代码,您可以简单地请求它,尽管我认为没有必要.谢谢.

I have been trying to create an online game but when I try to use socket.on(...); or socket.emit(...) it comes up with an error like what is socket. I have seen some posts similar to this one and tried all the solutions but none worked. I have already got io.connect(...); working and it works (I assume this means I have properly set up socket.io-client). I just don't see what I am doing wrong. If you need the code you can simply request it though I don't think it was necessary. Thanks.

推荐答案

要在客户端使用SocketIO,首先通过

To use SocketIO on the client-side, first import it via

import * as io from 'socket.io-client';

然后,可能在构造函数中,建立到运行 SocketIO 服务器的服务器 ip 和端口的连接

Then, probably in a constructor, establish a connection to the server's ip and port running the SocketIO server

const socket = io(`172.16.1.3:81`);

同样在构造函数中,您可能希望设置一个函数,以便在服务器发送特定消息类型时调用:

Also in the constructor you will likely want to setup a function to be called when the server sends a certain message type:

socket.on("update-player", handlePlayerUpdateFunction);

function handlePlayerUpdateFunction(message) {
    console.log(`Received message from server: ${message}`);
}

如果此客户端没有收到您的服务器发送的消息,则说明您的服务器没有正确设置以侦听端口.

If this client does not receive the message sent from your server, then something is wrong with your server not being set up correctly to listen on the port.

这篇关于如何在客户端导入 socket.io - SOCKET.IO + NODE.JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆