websocket 使用localhost能连接,使用IP地址不能连接问题

ws://localhost:8088  可以正常访问 改为 ws://192.168.1.120:8088 就不可以访问,

原因就是获取不到session信息

解决方法:需要浏览器输入的项目地址和建立websocket连接的地址一样

这里提供一个使用Vue.js和C++的WebSocket通信代码示例。 在Vue.js中,可以使用Vue-socket.io插件来实现WebSocket通信。首先,使用npm安装该插件: ``` npm install vue-socket.io ``` 然后在Vue组件中引入并使用该插件: ```javascript import VueSocketIO from 'vue-socket.io'; import io from 'socket.io-client'; Vue.use(new VueSocketIO({ debug: true, connection: io('http://localhost:3000') // WebSocket服务器地址 })); ``` 在C++中,可以使用Boost.Asio库来实现WebSocket通信。以下是一个简单的C++ WebSocket服务器示例: ```cpp #include <boost/asio.hpp> #include <boost/beast/core.hpp> #include <boost/beast/websocket.hpp> #include <iostream> #include <string> namespace beast = boost::beast; namespace http = beast::http; namespace websocket = beast::websocket; namespace net = boost::asio; using tcp = net::ip::tcp; int main() { try { net::io_context ioc; tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 3000)); while (true) { tcp::socket socket(ioc); acceptor.accept(socket); try { websocket::stream<tcp::socket> ws(std::move(socket)); ws.accept(); while (true) { beast::flat_buffer buffer; websocket::message_type msg_type; ws.read(buffer, msg_type); if (msg_type == websocket::message_type::text) { std::string message(beast::buffers_to_string(buffer.data())); std::cout << "Received message: " << message << std::endl; // 在这里处理接收到的消息并回复 std::string reply = "Server received message: " + message; ws.write(net::buffer(reply)); } } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } } } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return -1; } return 0; } ``` 这个示例代码使用Boost.Asio库实现了一个WebSocket服务器,并通过TCP端口3000监听连接请求。服务器在收到客户端发送的消息后,会将消息回复给客户端。 在Vue.js中,可以通过以下方式向WebSocket服务器发送消息: ```javascript this.$socket.emit('message', 'Hello, WebSocket server!'); ``` 这将向WebSocket服务器发送一个名为“message”的事件,并将字符串“Hello, WebSocket server!”作为参数传递。在C++ WebSocket服务器中,可以通过以下方式接收客户端发送的消息: ```cpp ws.read(buffer, msg_type); if (msg_type == websocket::message_type::text) { std::string message(beast::buffers_to_string(buffer.data())); std::cout << "Received message: " << message << std::endl; // 在这里处理接收到的消息并回复 std::string reply = "Server received message: " + message; ws.write(net::buffer(reply)); } ``` 这将从WebSocket读取一个消息,并在消息类型为文本时将其转换为字符串。然后,可以在服务器上处理接收到的消息,并通过WebSocket向客户端发送回复。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值