MCPcopy
hub / github.com/robtaussig/react-use-websocket / createOrJoinSocket

Function createOrJoinSocket

src/lib/create-or-join.ts:42–117  ·  view source on GitHub ↗
(
  webSocketRef: MutableRefObject<WebSocketLike | null>,
  url: string,
  setReadyState: (readyState: ReadyState) => void,
  optionsRef: MutableRefObject<Options>,
  setLastMessage: (message: WebSocketEventMap['message']) => void,
  startRef: MutableRefObject<() => void>,
  reconnectCount: MutableRefObject<number>,
  sendMessage: SendMessage,
)

Source from the content-addressed store, hash-verified

40};
41
42export const createOrJoinSocket = (
43 webSocketRef: MutableRefObject<WebSocketLike | null>,
44 url: string,
45 setReadyState: (readyState: ReadyState) => void,
46 optionsRef: MutableRefObject<Options>,
47 setLastMessage: (message: WebSocketEventMap['message']) => void,
48 startRef: MutableRefObject<() => void>,
49 reconnectCount: MutableRefObject<number>,
50 sendMessage: SendMessage,
51): (() => void) => {
52 if (!isEventSourceSupported && optionsRef.current.eventSourceOptions) {
53 if (isReactNative) {
54 throw new Error('EventSource is not supported in ReactNative');
55 } else {
56 throw new Error('EventSource is not supported');
57 }
58 }
59
60 if (optionsRef.current.share) {
61 let clearSocketIoPingInterval: ((() => void) | null) = null;
62 if (sharedWebSockets[url] === undefined) {
63 sharedWebSockets[url] = optionsRef.current.eventSourceOptions ?
64 new EventSource(url, optionsRef.current.eventSourceOptions) :
65 new WebSocket(url, optionsRef.current.protocols);
66 webSocketRef.current = sharedWebSockets[url];
67 setReadyState(ReadyState.CONNECTING);
68 clearSocketIoPingInterval = attachSharedListeners(
69 sharedWebSockets[url],
70 url,
71 optionsRef,
72 sendMessage,
73 );
74 } else {
75 webSocketRef.current = sharedWebSockets[url];
76 setReadyState(sharedWebSockets[url].readyState);
77 }
78
79 const subscriber: Subscriber = {
80 setLastMessage,
81 setReadyState,
82 optionsRef,
83 reconnectCount,
84 reconnect: startRef,
85 };
86
87 addSubscriber(url, subscriber);
88
89 return cleanSubscribers(
90 url,
91 subscriber,
92 optionsRef,
93 setReadyState,
94 clearSocketIoPingInterval,
95 );
96 } else {
97 webSocketRef.current = optionsRef.current.eventSourceOptions ?
98 new EventSource(url, optionsRef.current.eventSourceOptions) :
99 new WebSocket(url, optionsRef.current.protocols);

Callers 2

startFunction · 0.90

Calls 4

attachSharedListenersFunction · 0.90
addSubscriberFunction · 0.90
attachListenersFunction · 0.90
cleanSubscribersFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…