简体   繁体   中英

WebSocket in the app

I do not speak English well, so sorry. Here is my working WebSocket, which works in the browser. I need to write it to my application (react native). Please help me write it. I can not figure it out for two days already.

 <html> <head> <meta charset="utf-8"> <title>charset</title> </head> <script> reader = new FileReader(); reader.onload = function() { alert(reader.result); } var socket = new WebSocket("ws://77.87.917.23:8023", 'binary'); socket.onopen = function() { alert("Соединение установлено."); }; socket.onclose = function(event) { if (event.wasClean) { alert('Соединение закрыто чисто'); } else { alert('Обрыв соединения'); } alert('Код: ' + event.code + ' причина: ' + event.reason); }; socket.onmessage = function(event) { reader.readAsText(event.data); }; </script> </html> 

You can use it by this way.You can create instance of socket in component constructor or componentDidMount function.

import io from 'socket.io-client';

const socket = io.connect("http://77.87.917.23:8023",transports: ['websocket']});

socket.on('connect', (socket) => {
  console.log('Sono -> connect.');
});

//you can call this function on button click or any other way from the react native component
function sendData(data)
{
    socket.emit(event_name,data);// catch this event on server side
}

//This event is fire from server side
socket.on('exchange', function(data){
  console.log("share parametere",data);
});

If you have any query then feel free to ask me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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