serhiiz
serhiiz

Reputation: 141

Why does websocket close immediately after open in react native with code 1000. (iOS)

When I make a connection, the web socket closes immediately with code 1000. Can someone tell me why this happens?

Here is my simple code:

let ws = new WebSocket("wss://myhost/my-path?param1=value1&param2=value2")

ws.onopen = () => console.log('OPEN')
ws.onclose = (e) => console.log('CLOSE: code: ' + e.code)
ws.onmessage = (e) => console.log('MESSAGE: ', e.data)
ws.onerror = () => console.log('ERROR')
// The result is:
// OPEN
// CLOSE: code: 1000

React native information

$ react-native info

Environment:
  OS: macOS High Sierra 10.13.5
  Node: 8.9.4
  Yarn: 0.21.3
  npm: 5.7.1
  Watchman: 4.7.0
  Xcode: Xcode 9.4.1 Build version 9F2000
  Android Studio: 3.1 AI-173.4720617

Packages: (wanted => installed)
  react: 16.3.1 => 16.3.1
  react-native: 0.55.4 => 0.55.4

Upvotes: 6

Views: 3338

Answers (1)

serhiiz
serhiiz

Reputation: 141

Some servers can close connection automatically if client sends headers not completely. The WebSocket's constructor has 3rd undocumented parameter which can be used to add some headers. I just added the additional headers and there was no disconnection anymore.

// In this case server doesn't close the connection.
let ws = new WebSocket("wss://myhost/my-path?param1=value1&param2=value2", null, {
    headers: {
      'Accept-Language': 'en,en-US;q=0.9,ru;q=0.8,de;q=0.7',
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache',
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
    }
})

// In this case the server closes the connection.
let ws = new WebSocket("wss://myhost/my-path?param1=value1&param2=value2")

Upvotes: 8

Related Questions