Using Websocket Channel in React
I am working on a project where I have to make an api call to a websocket, and display certain information based on that call. As you can see I have used the subscribe portion of the channel in my call. Now I'm not sure what to do if anything with the 2nd two set of bracket. Do I need to include them my call as well, or do they come along with the subscription? And from which of them would I be using the information I need to display? In other words which one is the information I am recieving?
'''
const ws = new WebSocket("wss://ws-feed.exchange.coinbase.com");
const apiCall = {
type: "subscribe",
product_ids: [
"ETH-USD",
"BTC-USD"
],
channels: ["level2"]
};
ws.onopen = (event) => {
ws.send(JSON.stringify(apiCall));
};
ws.onmessage = function (event) {
const json = JSON.parse(event.data);
console.log(`[message] Data received from server: ${json}`);
};
'''
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
MarkLogic server-side JavaScript and XQuery
I am just starting using NoSQL MarkLogic DB and trying to choose for me the best query language to learn and use in future. On server side MarkLogic provides the possibility to use JavaScript API or XQuery API.
I want to receive an advice. Which language is better to concentrate on and learn? JavaScript or XQuery?
- Popover in chrome extension using js
-
react-router-dom v6 params only numbers
I want add number regex in may param in react-router-dom v6. it work fin in v5 like it:
<Route path="list/:id(\d+)" element={<MyComponent/>} />
but it not work in v6.
-
How can I fixed my problem"FirebaseError: Firebase: Error (auth/invalid-api-key)."
My environment variable is ok. No comas and name mistakes but they given me error like "FirebaseError: Firebase: Error (auth/invalid-api-key)". How can I fixed it. Please Help me...
This my .env file
REACT_APP_apiKey=AIzaSyBWobnhbdeMdNpXXXXXXXXXXXXXXXXXXXX REACT_APP_authDomain=XXXXX.firebaseapp.com REACT_APP_projectId=XXXX REACT_APP_storageBucket=XXXXX.appspot.com REACT_APP_messagingSenderId=4997390XXXXX REACT_APP_appId=1:4997390XXXXX:web:cc7bc80aa1bdb78fXXXXXX REACT_APP_measurementId=G-M1XDXXXXXX
This my firebase config file
const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId: process.env.REACT_APP_measurementId, }; when I debugging firebaseConfig object console.log(firebaseConfig.apiKey); ==========> undefined console.log(firebaseConfig.authDomain); ==========> undefined console.log(firebaseConfig.projectId); ==========> undefined console.log(firebaseConfig.storageBucket); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined console.log(firebaseConfig.appId); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined
client side given error this "FirebaseError: Firebase: Error (auth/invalid-api-key)"
-
Images with Firebase and Python Flask API
I am currently developing an API using Firebase from google and Python's Flask libraries. It is a proyect where I am in need of saving images to the DB and then adress them in the API. I would also like to know how to relate the image to an item in the database, say posting an image of Juan, and that is linked with ALL the information from Juan inside the DB. Thanks!
-
Need help finding an api or real world data related to read time of people
I need to create a project for which I require real world data of reading time per page or article. Can anyone help me find data or api in which I can get this data I tried to search for some api but they had information related to books instead of their reading time of a person.
-
Websocket with special characters
I am using websocket with client nodejs and server golang (net library) via tcp. I am read data sent from client but many special chars. Some one can help me about that?
Data received:
\u0016\u0003\u0001\u0002\u0000\u0001\u0000\u0001\ufffd\u0003\u0003x\ufffd_\ufffdj\ufffd\ufffd\ufffd\ufffdȬ{\ufffd \ufffdI\u003c9\u000bC1YŲ\ufffdVp\u0017\ufffd\u000e`\ufffd \ufffd\ufffd\ufffd\u0017\ufffd\ufffd=\\u0002\ufffd~,\u0011\ufffdn\ufffd\ufffdY\u0010\ufffd\u001c\ufffdw\u000f\ufffd\ufffd(hfK\ufffd\ufffd\u0000 \u001a\u001a\u0013\u0001\u0013\u0002\u0013\u0003\ufffd+\ufffd/\ufffd,\ufffd0̨̩\ufffd\u0013\ufffd\u0014\u0000\ufffd\u0000\ufffd\u0000/\u00005\u0001\u0000\u0001\ufffd\ufffd\ufffd\u0000\u0000\u0000\u0000\u0000\u0014\u0000\u0012\u0000\u0000\u000fvenus.localhost\u0000\u0017\u0000\u0000\ufffd\u0001\u0000\u0001\u0000\u0000"
This func use to accept tcp
func (s *WebsocketServer) Serve() { if s.running { return } s.running = true for _, lsn := range s.lsnList { for i := 0; i < s.accepts; i++ { go func(lsn2 *net.TCPListener) { var ( conn *net.TCPConn err error ) for { if conn, err = AcceptTCP(lsn2); err != nil { // if listener close then return log.Error("listener.Accept(\"%s\") error(%v)", lsn2.Addr().String(), err) return } if err = conn.SetKeepAlive(s.c.Keepalive); err != nil { log.Error("conn.SetKeepAlive() error(%v)", err) return } if err = conn.SetReadBuffer(s.c.ReceiveBuf); err != nil { log.Error("conn.SetReadBuffer() error(%v)", err) return } if err = conn.SetWriteBuffer(s.c.SendBuf); err != nil { log.Error("conn.SetWriteBuffer() error(%v)", err) return } go s.establishWebsocketConnection(conn) } }(lsn) } } } func (s *WebsocketServer) establishWebsocketConnection(conn net.Conn) { var ( // conn2 = NewBufferedConnSize(conn, 66560) req *websocket.Request websocketConn *websocket.Conn err error ) rr := bufio.NewReader(conn) if req, err = websocket.ReadRequest(rr); err != nil || req.RequestURI != "/apiws" { conn.Close() if err != io.EOF { log.Errorf("websocket.ReadRequest(rr) error(%v)", err) } return } else { wr := bufio.NewWriter(conn) websocketConn, err = websocket.Upgrade(conn, rr, wr, req) if err != nil { log.Errorf("websocket.Upgrade(rr) error(%v)", err) conn.Close() return } } codec, err := NewCodecByName(s.c.ProtoName, websocketConn) tcpConn := NewTcpConnection2(s.c.ServerName, websocketConn, s.c.SendChanSize, codec, true, s) // log.Info("establishTcpConnection...") defer func() { if err := recover(); err != nil { log.Error("tcp_server handle panic: %v\n%s", err, debug.Stack()) tcpConn.Close() } }() s.onNewConnection(tcpConn) for { tcpConn.conn.SetReadDeadline(time.Now().Add(time.Minute * 6)) msg, err := tcpConn.Receive() if err != nil { log.Error("conn: %s recv error: %v", tcpConn, err) return } if msg == nil { log.Error("recv a nil msg by conn: %s", tcpConn) continue } if s.callback != nil { // log.Info("onConnectionDataArrived - conn: %s", conn) if err := s.callback.OnConnectionDataArrived(tcpConn, msg); err != nil { } } } }
Function from websocket file, I print data here like above
func ReadRequest(r *bufio.Reader) (req *Request, err error) { var ( b []byte ok bool ) req = &Request{reader: r} if b, err = req.readLine(); err != nil { return } log.Errorf("websocket.ReadRequest: %s", string(b)) if req.Method, req.RequestURI, req.Proto, ok = parseRequestLine(string(b)); !ok { return nil, fmt.Errorf("malformed HTTP request %s", b) } if req.Header, err = req.readMIMEHeader(); err != nil { return } req.Host = req.Header.Get("Host") return req, nil } func (r *Request) readLine() ([]byte, error) { var line []byte for { l, more, err := r.reader.ReadLine() if err != nil { return nil, err } // Avoid the copy if the first call produced a full line. if line == nil && !more { return l, nil } line = append(line, l...) if !more { break } } return line, nil }
Please help me
-
How to maintain a Websocket connection for my Angular(13.0.4) application across pages? I need to load the websocket url into service not at the start
So this is my web-socket.service.ts where I send the url information to the websocket in order to establish the connection:
import { Injectable } from '@angular/core'; import { Observable, Observer, Subject } from 'rxjs'; import { AnonymousSubject } from 'rxjs/internal/Subject'; import { Message } from './ws-message.type' import { Router} from '@angular/router'; @Injectable({ providedIn: 'root' }) export class WebSocketService { private subject: AnonymousSubject<MessageEvent>; public messages: Subject<Message>; private jwt: string; constructor(private router: Router) { } public connect(url): AnonymousSubject<MessageEvent> { if (!this.subject) { this.subject = this.create(url); console.log("Successfully connected: " + url); } return this.subject; } private create(url): AnonymousSubject<MessageEvent> { let ws = new WebSocket(url); let observable = new Observable((obs: Observer<MessageEvent>) => { ws.onmessage = obs.next.bind(obs); ws.onerror = obs.error.bind(obs); ws.onclose = obs.complete.bind(obs); return ws.close.bind(ws); }); let observer = { error: null, complete: null, next: (data: Object) => { console.log('Message sent to websocket: ', data); if (ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify(data)); } } }; return new AnonymousSubject<MessageEvent>(observer, observable); } }
Currently I make the connection on my typescript by:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { environment } from 'src/environments/environment'; import { webSocket } from 'rxjs/webSocket'; import { MenuController } from '@ionic/angular'; @Component({ selector: 'app-org', templateUrl: './org.page.html', styleUrls: ['./org.page.scss'], }) export class OrgPage implements OnInit { jwt: string; ws_session; stringObject: any; stringJson: any; content:any = []; constructor(public menuCtrl: MenuController, private router: Router) { this.jwt = sessionStorage.getItem("jwt"); if (this.jwt) { this.ws_session = webSocket(environment.WS_API_URL + '/connect/' + this.jwt); this.ws_session.subscribe(msg => { if (msg.action == "get_my_orgs"){ this.content = Object.assign(msg.content); this.stringJson = JSON.stringify(this.content); this.stringObject = JSON.parse(this.stringJson); console.log("JSON object -", this.stringObject); } }); } }
The connection currently works, but I create a new connection every page. I only want one connection across all pages as soon as I make the call to establish the connection. I'd like to know how to close the connection as well.
-
Why does client not receive final server answer in non-blocking client-server app?
I am trying to figure out NIO in Java doing some simple client-server project.
The case is I have to concurrent clients in cached thread pool executor, who are communicating with single-threaded server using non-blocking NIO channels.
The problem is that last client cannot receive last server's sent message. It locks in infinite loop waiting for upcoming data.
ClientTask class:
public class ClientTask extends FutureTask<String> { private Client client; private List<String> reqList; // requests list (without last and first) private boolean showRes; // print request results public ClientTask(Client client, List<String> reqList, boolean showRes) { super(() -> ClientTask.getLogWhenArrives(client, reqList, showRes)); this.client = client; this.reqList = reqList; this.showRes = showRes; } public static ClientTask create(Client c, List<String> reqList, boolean showRes) { return new ClientTask(c, reqList, showRes); } private static String getLogWhenArrives(Client client, List<String> reqList, boolean showRes) { client.connect(); String response = client.send("login " + client.getId()); if (showRes) System.out.println(response); for (String req : reqList) { response = client.send(req); if (showRes) System.out.println(response); } String responseLog = client.send("bye and log transfer"); client.close(); return responseLog; } }
Client send():
public String send(String req) { ByteBuffer reqBuffer = ByteBuffer.wrap((req + END).getBytes()); try { channel.write(reqBuffer); } catch (IOException e) { e.printStackTrace(); } return receive(); }
Client receive()
public String receive() { StringBuilder result = new StringBuilder(); try { inBuff.clear(); readLoop: while (true) { // THIS LOOP WON'T END int n = channel.read(inBuff); if (n == -1) { break; } if (n > 0) { inBuff.flip(); CharBuffer cb = charset.decode(inBuff); while (cb.hasRemaining()) { char c = cb.get(); if (c == END.charAt(0)) { break readLoop; } result.append(c); } } } } catch (IOException e) { e.printStackTrace(); } return result.toString(); }
Main:
public class Main { public static void main(String[] args) throws Exception { String fileName = System.getProperty("user.home") + "/PassTimeServerOptions.yaml"; Options opts = Tools.createOptionsFromYaml(fileName); String host = opts.getHost(); int port = opts.getPort(); boolean concur = opts.isConcurMode(); boolean showRes = opts.isShowSendRes(); Map<String, List<String>> clRequests = opts.getClientsMap(); ExecutorService es = Executors.newCachedThreadPool(); List<ClientTask> ctasks = new ArrayList<>(); List<String> clogs = new ArrayList<>(); Server s = new Server(host, port); s.startServer(); // start clients clRequests.forEach( (id, reqList) -> { Client c = new Client(host, port, id); if (concur) { ClientTask ctask = ClientTask.create(c, reqList, showRes); ctasks.add(ctask); es.execute(ctask); } }); if (concur) { ctasks.forEach( task -> { try { String log = task.get(); clogs.add(log); } catch (InterruptedException | ExecutionException exc) { System.out.println(exc); } }); clogs.forEach( System.out::println); es.shutdown(); } s.stopServer(); System.out.println("\n=== Server log ==="); System.out.println(s.getServerLog()); } }
Server is sending all the info and channels are open and connected.
-
Should I cancel the key when SocketChannel#connect returns true?
When
SocketChannel#connect
returns atrue
for a selector-registeredSocketChannel
, should I cancel theSelectionKey
?final var client = SocketChannel.open(); client.configureBlocking(false); final var key = client.register(selector, OP_CONNECT); if (client.connect(endpoint)) { // connected, immediately key.cancel(); // Should I do this? ... }
-
SocketChannel close() in thread (Java NIO)
I'm coding a multi user textual game (typical MUD) and I got the server code from another project using the NIO library.
Here is the server code of run method for main connections handle (running in dedicated thread):
public void run() { try { // block until a Channel is ready for I/O while (readSelector.select() > 0) { try { Iterator<SelectionKey> selectionKeyIter = readSelector.selectedKeys().iterator(); while (selectionKeyIter.hasNext()) { SelectionKey sk = selectionKeyIter.next(); selectionKeyIter.remove(); if (sk.isAcceptable()) { // new client connection ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel(); SocketChannel channel = nextReady.accept(); channel.configureBlocking(false); channel.register(readSelector, SelectionKey.OP_READ); writeSelector.wakeup(); // Added as required by specification channel.register(writeSelector, SelectionKey.OP_WRITE); ConnectionManager.add(channel); } else if (sk.isValid() && sk.isConnectable()) { } else if (sk.isValid() && sk.isReadable()) { try { readSocket(sk); } catch (IOException ioe) { ConnectionManager.close(sk); throw ioe; } } else if (sk.isValid() && sk.isWritable()) { } else if (!sk.isValid()) { new MudException("SelectionKey not valid:"); } } } catch (Throwable t) { LOGGER.error("Communication error", t); } } } catch (Exception e) { LOGGER.error("Communication channel error", e); } } private void readSocket(SelectionKey sk) throws IOException { SocketChannel socketChannel = (SocketChannel) sk.channel(); buffer.clear(); int numberOfBytesRead; numberOfBytesRead = socketChannel.read(buffer); if (numberOfBytesRead == -1) { LOGGER.info("Connection closed by " + socketChannel.getRemoteAddress()); socketChannel.close(); sk.cancel(); return; } buffer.flip(); cb = Charset.forName("UTF-8").decode(buffer); sb = new StringBuilder(); int remaining = cb.remaining(); for (int i = 0; i < remaining; i++) { char c = (char) cb.get(); if (c > 31 && c < 256) { sb.append(c); } } if (sb.length() < 1) { sb.append(""); } ConnectionManager.process(socketChannel, sb.toString().trim()); }
Then I implemented the command to quit the game in this way:
public void quitCommand(Player p) { toPlayer(p, "Bye!"); // send msg to player p.disconnect(); // call player's SocketChannel.close() p.remove(); // remove player from players array } // disconnect method of Player class called above public void disconnect() { try { // sc is player's SocketChannel sc.socket().close(); sc.close(); } catch (IOException e) { LOGGER.error("Error closing connection", e); } }
and it works correctly!
Then I modified this method in order to implement a countdown before disconnecting, keeping the player able to types command during the countdown (so the player can stop disconnection or performing other actions).
To achieve it I used Timer and TimerTask classes:
public void quitCommand(Player p) { LOGGER.info("Disconnecting player " + p.getName()); Timer timer = new Timer(); TimerTask quit = new TimerTask() { short counter = 5; @Override public void run() { if (p.getAction() != Player.QUITTING) { // check if other action perfomed timer.cancel(); toPlayer(p, "Disconnection aborted"); // send msg to player return; } if (counter > 0) { toPlayer(p, "Disconnecting in " + counter + " seconds..."); counter--; } else { toPlayer(p, "Bye!"); p.disconnect(); p.remove(); timer.cancel(); } } }; timer.scheduleAtFixedRate(quit, 0, 1000); }
In this case, after player disconnection, if I try to reconnect to the server, the client (telnet) seems freezed:
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'.
I tried to use Thread instead of TimerTask with the same result.
I noticed that if two players are simultaneously connected and one of them disconnects the client of the other one freezes as above.
I suppose it is probably a thread issue with SocketChannel, but I cannot understand the reason since each player has its own SocketChannel.