我英语说得不好,所以抱歉。这是我的工作 WebSocket,它在浏览器中工作。我需要将其写入我的应用程序( react native )。请帮我写一下。我已经两天没弄清楚了。
<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>
最佳答案
可以通过这种方式使用它。您可以在组件构造函数或 componentDidMount 函数中创建套接字实例。
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);
});
如果您有任何疑问,请随时询问我。
关于javascript - 应用程序中的 WebSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48418361/