or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-api.mdevents.mdindex.mdtransports.md

index.mddocs/

0

# SockJS-client

1

2

SockJS-client is a browser JavaScript library that provides a WebSocket-like object for establishing cross-browser, full-duplex communication channels between browsers and web servers. It creates low-latency, cross-domain communication by first attempting to use native WebSockets and falling back to various browser-specific transport protocols when WebSockets are unavailable.

3

4

The library maintains compatibility with the HTML5 WebSocket API while providing robust fallback mechanisms for older browsers and constrained network environments, including support for restrictive corporate proxies and cross-domain connections.

5

6

## Package Information

7

8

- **Package Name**: sockjs-client

9

- **Package Type**: npm

10

- **Language**: JavaScript

11

- **Installation**: `npm install sockjs-client`

12

- **CDN**: `https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js`

13

14

## Core Imports

15

16

For browser environments using CDN:

17

18

```html

19

<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>

20

```

21

22

For Node.js or bundlers:

23

24

```javascript

25

const SockJS = require('sockjs-client');

26

```

27

28

ES modules:

29

30

```javascript

31

import SockJS from 'sockjs-client';

32

```

33

34

## Basic Usage

35

36

```javascript

37

// Create connection

38

const sock = new SockJS('https://mydomain.com/my_prefix');

39

40

// Set up event handlers

41

sock.onopen = function() {

42

console.log('Connected');

43

sock.send('Hello Server!');

44

};

45

46

sock.onmessage = function(e) {

47

console.log('Received:', e.data);

48

};

49

50

sock.onclose = function() {

51

console.log('Disconnected');

52

};

53

54

sock.onerror = function() {

55

console.log('Connection error');

56

};

57

58

// Later: close connection

59

sock.close();

60

```

61

62

## Architecture

63

64

SockJS-client is built around several key components:

65

66

- **SockJS Class**: Main WebSocket-like interface providing connection management and message handling

67

- **Transport System**: Automatic fallback mechanism supporting 11+ transport protocols from WebSocket to JSONP polling

68

- **Event System**: DOM-compatible event handling with support for both handler properties and addEventListener

69

- **Browser Detection**: Intelligent capability detection to select the most appropriate transport for each environment

70

- **Cross-Domain Support**: Built-in support for cross-origin requests with cookie-based sticky sessions

71

72

## Capabilities

73

74

### Core Connection API

75

76

Primary SockJS class providing WebSocket-compatible interface for establishing and managing connections with automatic transport fallback.

77

78

```javascript { .api }

79

/**

80

* SockJS constructor - creates a new SockJS connection

81

* @param {string} url - Connection URL (http/https), may contain query string

82

* @param {string|string[]} [protocols] - Protocols (reserved parameter, typically not used)

83

* @param {object} [options] - Configuration options

84

*/

85

function SockJS(url, protocols, options);

86

87

// Instance properties

88

SockJS.prototype.url; // string - Connection URL

89

SockJS.prototype.readyState; // number - Current connection state (0-3)

90

SockJS.prototype.extensions; // string - Always empty string

91

SockJS.prototype.protocol; // string - Always empty string

92

SockJS.prototype.transport; // string - Active transport name when connected

93

94

// Instance methods

95

SockJS.prototype.send(data); // Send data (converts non-strings to strings)

96

SockJS.prototype.close(code, reason); // Close connection with optional code and reason

97

98

// Static constants

99

SockJS.CONNECTING; // 0 - Connection being established

100

SockJS.OPEN; // 1 - Connection is open

101

SockJS.CLOSING; // 2 - Connection is closing

102

SockJS.CLOSED; // 3 - Connection is closed

103

104

// Static property

105

SockJS.version; // string - Library version

106

```

107

108

[Core Connection API](./core-api.md)

109

110

### Event System

111

112

DOM-compatible event handling system supporting both event handler properties and addEventListener/removeEventListener methods.

113

114

```javascript { .api }

115

// Event handler properties

116

sock.onopen = function() { /* connection opened */ };

117

sock.onmessage = function(e) { /* message received: e.data */ };

118

sock.onclose = function(e) { /* connection closed: e.code, e.reason, e.wasClean */ };

119

sock.onerror = function() { /* connection error */ };

120

121

// EventTarget methods

122

sock.addEventListener(type, listener); // Add event listener

123

sock.removeEventListener(type, listener); // Remove event listener

124

sock.dispatchEvent(event); // Dispatch event

125

```

126

127

[Event System](./events.md)

128

129

### Transport Configuration

130

131

Flexible transport system with automatic fallback and manual configuration options for different network environments and browser capabilities.

132

133

```javascript { .api }

134

// Constructor options for transport configuration

135

const options = {

136

server: string, // Server identifier (default: random 4-digit number)

137

transports: string|Array, // Whitelist of allowed transports

138

sessionId: number|function, // Session ID generation (default: 8 chars)

139

timeout: number, // Minimum timeout for transport connections

140

transportOptions: object // Transport-specific configuration

141

};

142

143

// Available transport names for whitelisting

144

const availableTransports = [

145

'websocket',

146

'xhr-streaming',

147

'xdr-streaming',

148

'eventsource',

149

'iframe-eventsource',

150

'htmlfile',

151

'iframe-htmlfile',

152

'xhr-polling',

153

'xdr-polling',

154

'iframe-xhr-polling',

155

'jsonp-polling'

156

];

157

```

158

159

[Transport Configuration](./transports.md)

160

161

## Types

162

163

```javascript { .api }

164

// Options interface for SockJS constructor

165

interface SockJSOptions {

166

server?: string; // Server identifier

167

transports?: string | string[]; // Transport whitelist

168

sessionId?: number | (() => string); // Session ID configuration

169

timeout?: number; // Connection timeout

170

transportOptions?: object; // Transport-specific options

171

}

172

173

// Event objects

174

interface SockJSMessageEvent {

175

type: 'message';

176

data: any; // Message payload

177

}

178

179

interface SockJSCloseEvent {

180

type: 'close';

181

code: number; // Close code

182

reason: string; // Close reason

183

wasClean: boolean; // Clean close flag

184

}

185

186

interface SockJSEvent {

187

type: 'open' | 'error' | 'heartbeat';

188

}

189

```

190

191

## Limitations and Considerations

192

193

- **Connection Limit**: Only one SockJS connection per domain at a time due to browser connection limits

194

- **Data Types**: All data is converted to strings before transmission

195

- **Cross-Origin**: Requires server-side CORS support for cross-domain connections

196

- **Transport Cookies**: Some transports (XDR) don't support cookies, affecting sticky sessions

197

- **Protocol Support**: Only HTTP/HTTPS URLs are supported (no ws:// or wss://)

198

199

## Browser Compatibility

200

201

SockJS-client provides comprehensive browser support through its transport fallback system:

202

203

- **Modern Browsers**: WebSocket + XHR streaming/polling

204

- **IE 10+**: WebSocket + XHR streaming/polling

205

- **IE 8-9**: XDR streaming/polling or iframe-based transports

206

- **IE 6-7**: JSONP polling only

207

- **Legacy Browsers**: Graceful degradation to appropriate transport methods

208

209

The library automatically selects the best available transport based on browser capabilities and network environment.