React Native Websocket外部访问

时间:2017-06-21 19:42:19

标签: javascript react-native websocket

我试图从不包含websocket的组件发送我的websocket-server的答案。我的Websocket服务器如下所示:

    componentDidMount() {
    var ws = new WebSocket('ws:// URL');
    ws.onmessage = this.handleMessage.bind(this);
    ...
    }

我如何通过" var ws"到另一个类或组件。或者是否可以使websocket全局可访问? 非常感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

我在stackoverflow中找到了这个问题的帮助解决方案:

访问:

React native: Always running component

我创建了一个新类WebsocketController,如下所示:

    let instance = null;

    class WebsocketController{
        constructor() {
            if(!instance){
               instance = this;
            }
            this.ws = new WebSocket('ws://URL');
            return instance;
        }
    }

    export default WebsocketController

然后在我需要我的websocket的其他课程中,我就这样称呼它:

    let controller = new WebsocketController();
    var ws = controller.ws;

答案 1 :(得分:0)

websocket连接

将此代码保存在某个文件中,并使用.js扩展名命名。例如:websocket.js

var WebSocketServer = require("ws").Server;

var wss = new WebSocketServer({port:8100});

wss.broadcast = function broadcast(msg) {
    console.log(msg);
    wss.clients.forEach(function each(client) {
        client.send(msg);
    });
};

wss.on('connection', function connection(ws) {
    // Store the remote systems IP address as "remoteIp".
    var remoteIp = ws.upgradeReq.connection.remoteAddress;
    // Print a log with the IP of the client that connected.
    console.log('Connection received: ', remoteIp);

    ws.send('You successfully connected to the websocket.');

    ws.on('message',wss.broadcast);
});

在您的应用/网站方面。创建.js文件。例如:client.js

var SERVER_URL = 'ws://127.0.0.1:8100';
var ws;

function connect() {
  //alert('connect');
    ws = new WebSocket(SERVER_URL, []);
    // Set the function to be called when a message is received.
    ws.onmessage = handleMessageReceived;
    // Set the function to be called when we have connected to the server.
    ws.onopen = handleConnected;
    // Set the function to be called when an error occurs.
    ws.onerror = handleError;

}

function handleMessageReceived(data) {
    // Simply call logMessage(), passing the received data.
    logMessage(data.data);
}

function handleConnected(data) {
    // Create a log message which explains what has happened and includes
    // the url we have connected too.
    var logMsg = 'Connected to server: ' + data.target.url;
    // Add the message to the log.
    logMessage(logMsg)

    ws.send("hi am raj");
}

function handleError(err) {
    // Print the error to the console so we can debug it.
    console.log("Error: ", err);
}

function logMessage(msg) {
    // $apply() ensures that the elements on the page are updated
    // with the new message.
    $scope.$apply(function() {
        //Append out new message to our message log. The \n means new line.
        $scope.messageLog = $scope.messageLog + msg + "\n";
    });

}

如果您对此代码有任何疑问,请与我们联系