Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [JavaScript][node] Socket - odczytywanie objektu
Forum PHP.pl > Forum > Przedszkole
Johnas
Witam, używam websocket node bo potrzebuje... w momencie kiedy wysyłam wiadomość to nie jestem w stanie (nie wiem jak) odczytać danej zmiennej... tutaj mam funkcję odbierania przez serwer:

[JAVASCRIPT] pobierz, plaintext
  1. socket.on('connection', function connection(ws) {
  2. ws.on('message', function message(data) {
  3.  
  4. //var str = JSON.stringify(data);
  5. consloe.log(data);
  6. console.log('received: %s', data);
  7. //console.log(JSON.stringify(data));
  8. });
  9.  
  10. ws.send('something');
  11. });
[JAVASCRIPT] pobierz, plaintext


oraz wysyłanie przez clienta:

[JAVASCRIPT] pobierz, plaintext
  1. ws.onopen = function() {
  2. // subscribe to some channels
  3. ws.send(JSON.stringify({
  4. sid:"nfasmpdapk"
  5. }));
  6. };
[JAVASCRIPT] pobierz, plaintext


Chciałbym odczytać ten sid... próbowałem data[sid], data.sid, data["sid"] i żadna opcja nie działa... kiedyś robiłem to za pomocą php i było prościej bo mogłem wysłać wiadomość danemu klientowi, albo wszystkim... Tutaj nie widzę nawet id socketa...
etet100
W console literówka i nie ma żadnej informacji co te console.log właściwie zwraca.

Skoro w serwerze jest JSON.stringify to może w kliencie trzeba zdekodować przez console.log(JSON.parse(data)); ?
Johnas
tak, już to rozwiązałem, ale mam aktualnie inny problem:

[JAVASCRIPT] pobierz, plaintext
  1. socket.on('connection', function connection(ws, req) {
  2.  
  3. var userID = req.url.substr(1);
  4. clients.push({
  5. id: userID,
  6. wsoc: ws,
  7. isAlive: true,
  8. time: 0,
  9. });
[JAVASCRIPT] pobierz, plaintext


i dalej mam
[JAVASCRIPT] pobierz, plaintext
  1. ws.on("message", function incoming(message) {
  2. console.log(`[!] Message Receieved from ${req.socket.remoteAddress}`);
  3. msg = JSON.parse(message);
  4. console.log(clients);
  5. if ("action" in msg) {
  6. if (msg["action"] == "start") {
  7. if ("page" in user[userID]) {
  8. savePage(ws, user[userID]["page"]);
  9. user[userID]["page"] = msg["page"];
  10. user[userID][user[userID]["page"]] = 0;
  11. user[userID]["pos"] = 0;
  12. user[userID]["start"] = Date.now();
  13. socket.clients.forEach(function each(client) {
  14. console.log("set "+client.id);
  15. if (client.id === userID) {
  16. client.time = Date.now();
  17. console.log("Zmieniłem czas");
  18. }
  19. });
  20. } else {
  21. user[userID]["page"] = msg["page"];
  22. user[userID][user[userID]["page"]] = 0;
  23. user[userID]["pos"] = 0;
  24. }
  25. }
[JAVASCRIPT] pobierz, plaintext


nie wiem jak przypisać czas do client o danym id,

nie potrafię tego zrozumieć... Logi z konsoli... widać że czas czasem czasowi nie równy tongue.gif
Kod
zmieniam czas z 1650851119289 na 1650851134647
zmieniam czas z 1650851134595 na 1650851134647
1650851134805
1650851135806
1650851136808
1650851137810
1650851138812
Message was sent
Message was sent
[!] Message Receieved from ::ffff:37.47.175.153
pos
obywatel na stronie przez 5 sekund
1650851139813
[-] sid has Disconnected.
client disconnected 1650851134647<1650851140789
1650851140814
1650851141816
1650851142817
1650851143819
etet100
Tobie się chyba wydaje że ludzie czytają w myślach. Te logi nawet nie zgadzają się z kodem.
Johnas
chodzi mi o to że gdy ktoś odświeży stronę to crashuje mi połączenie z socketami... chcę aby połączenie było dalej podtrzymywane...

Tutaj cały kod serwera... chciałem liczyć 5 sekund, ale niestety to nie pomaga tongue.gif

[JAVASCRIPT] pobierz, plaintext
  1. const WebSocket = require("ws").Server;
  2. const HttpsServer = require('https').createServer;
  3. const fs = require("fs");
  4. var keys = [];
  5. var clients = [];
  6. var user = [];
  7. var timenow = Date.now();
  8.  
  9. function heartbeat() {
  10. this.isAlive = true;
  11. }
  12.  
  13. keys["oxi-jon.pl"] = "samba";
  14.  
  15. server = HttpsServer({
  16. cert: fs.readFileSync('/etc/letsencrypt/live/websocket.oxi-jon.pl/cert.pem'),
  17. key: fs.readFileSync('/etc/letsencrypt/live/websocket.oxi-jon.pl/privkey.pem')
  18. })
  19. socket = new WebSocket({
  20. server: server
  21. });
  22.  
  23. socket.on('connection', function connection(ws, req) {
  24.  
  25. var userID = req.url.substr(1);
  26. clients.push({
  27. id: userID,
  28. wsoc: ws,
  29. isAlive: true,
  30. });
  31.  
  32. if (userID in user) {
  33. return true;
  34. } else {
  35. user[userID] = []
  36. }
  37.  
  38. user[userID]["ws"] = ws;
  39. /*clients[userID] = [];
  40. clients[userID]["ws"] = ws;
  41. console.log('Połączono: ' + userID + ' in ' + Object.getOwnPropertyNames(clients));*/
  42.  
  43. console.log(`[+] ${req.socket.remoteAddress} Connected`);
  44.  
  45. socket.clients.forEach(function each(client) {
  46. if (client.readyState === WebSocket.OPEN) {
  47. message = {
  48. type: "alert",
  49. msg: `${queryData.id} has Connected.`,
  50. };
  51. console.log("Connected`");
  52. client.send(JSON.stringify(message), { binary: false });
  53. }
  54. });
  55.  
  56. ws.on("message", function incoming(message) {
  57. console.log(`[!] Message Receieved from ${req.socket.remoteAddress}`);
  58. msg = JSON.parse(message);
  59. if ("action" in msg) {
  60. if (msg["action"] == "start") {
  61. console.log("action")
  62. if ("page" in user[userID]) {
  63. if (user[userID]["page"] != msg["page"]) {
  64. savePage(user[userID]["page"]);
  65. user[userID]["page"] = msg["page"];
  66. user[userID][user[userID]["page"]] = 0;
  67. user[userID]["pos"] = 0;
  68. changewsoc(user[userID]["ws"]);
  69. } else {
  70. return true;
  71. }
  72.  
  73.  
  74.  
  75. } else {
  76. console.log("nie ma page");
  77. user[userID]["page"] = msg["page"];
  78. user[userID][user[userID]["page"]] = 0;
  79. user[userID]["pos"] = 0;
  80. changewsoc(user[userID]["ws"]);
  81. }
  82. } else {
  83. // continue
  84. if ("pos" in user[userID]) {
  85. console.log("pos");
  86. if (user[userID]["pos"] != msg["pos"]) {
  87. user[userID]["pos"] = msg["pos"];
  88. user[userID][user[userID]["page"]] += 5;
  89. console.log("obywatel na stronie przez "+user[userID][user[userID]["page"]]+" sekund");
  90. } else {
  91. console.log("obywatel AFK");
  92. }
  93. }
  94. }
  95. }
  96.  
  97.  
  98. msg = { ...msg, time: new Date().toISOString() };
  99. socket.clients.forEach(function each(client) {
  100. if (client.readyState === WebSocket.OPEN) {
  101. client.send(JSON.stringify(msg), { binary: false });
  102. }
  103. });
  104. });
  105.  
  106. ws.isAlive = true;
  107. ws.on('pong', heartbeat);
  108. });
  109. /*
  110. socket.addListener("customClose", function (m) {
  111.   socket.clients.forEach(function each(client) {
  112.   if (client.readyState === WebSocket.OPEN) {
  113.   message = {
  114.   type: "alert",
  115.   msg: `${m} has Disconnected.`,
  116.   };
  117.   client.send(JSON.stringify(message), { binary: false });
  118.   }
  119.   });
  120. });*/
  121.  
  122. function getData(ws) {
  123. // console.log("checking time!");
  124.  
  125. var message = {
  126. "get": "data"
  127. };
  128. ws.send(JSON.stringify(message));
  129. console.log("Message was sent");
  130.  
  131. }
  132.  
  133. function changewsoc(ws) {
  134. clients.forEach((clnt, index) => {
  135. clnt.wsoc = ws;
  136. });
  137. }
  138.  
  139. function savePage(page, time, domain) {
  140. console.log(key[domain]);
  141. }
  142.  
  143. const interval = setInterval(function ping() {
  144. socket.clients.forEach(function each(ws) {
  145. if (ws.isAlive === false) {
  146. //console.log(ws);
  147. //savePage(user[ws.id], time, domain)
  148. return ws.terminate();
  149. } else {
  150. getData(ws)
  151. }
  152. //console.log(ws);
  153. ws.isAlive = false;
  154. ws.ping();
  155. });
  156. }, 5000);
  157.  
  158.  
  159. server.listen(1111);
[JAVASCRIPT] pobierz, plaintext




Zamyka mi samo połączenie, w konsoli mam coś takiego po otrzymaniu wiadomości :

Kod
Message: {"get":"data"}
client.js:33 Socket is closed. Reconnect will be attempted in 1 second.
client.js:16 message
client.js:70 position=0
client.js:20 Object
client.js:21 Message: {"get":"data"}
client.js:33 Socket is closed. Reconnect will be attempted in 1 second.
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.