> For the complete documentation index, see [llms.txt](https://www.rxjs.es/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.rxjs.es/api/websocket/websocketsubjectconfig.md).

# WebSocketSubjectConfig

## WebSocketSubjectConfig es un Objeto sencillo que permite configurar un WebSocket

```typescript
interface WebSocketSubjectConfig<T> {
  url: string
  protocol?: string | Array<string>
  resultSelector?: (e: MessageEvent) => T
  serializer?: (value: T) => WebSocketMessage
  deserializer?: (e: MessageEvent) => T
  openObserver?: NextObserver<Event>
  closeObserver?: NextObserver<CloseEvent>
  closingObserver?: NextObserver<void>
  WebSocketCtor?: {...}
  binaryType?: 'blob' | 'arraybuffer'
}
```

## Descripciṕn

Proporciona flexibilidad a webSocket.

It defines a set of properties to provide custom behavior in specific moments of the socket's lifecycle. When the connection opens we can use openObserver, when the connection is closed closeObserver, if we are interested in listening for data comming from server: deserializer, which allows us to customize the deserialization strategy of data before passing it to the socket client. By default deserializer is going to apply JSON.parse to each message comming from the Server.

## Ejemplos

deserializer, the default for this property is JSON.parse but since there are just two options for incomming data, either be text or binarydata. We can apply a custom deserialization strategy or just simply skip the default behaviour.

```javascript
import { webSocket } from 'rxjs/webSocket';

const wsSubject = webSocket({
url: 'ws://localhost:8081',
//Apply any transformation of your choice.
deserializer: ({data}) => data
});

wsSubject.subscribe(console.log);

// Let's suppose we have this on the Server: ws.send("This is a msg from the server")
//output
//
// This is a msg from the server
serializer allows us tom apply custom serialization strategy but for the outgoing messages
```

```javascript
import { webSocket } from 'rxjs/webSocket';

const wsSubject = webSocket({
url: 'ws://localhost:8081',
//Apply any transformation of your choice.
serializer: msg => JSON.stringify({channel: "webDevelopment", msg: msg})
});

wsSubject.subscribe(() => subject.next("msg to the server"));

// Let's suppose we have this on the Server: ws.send("This is a msg from the server")
//output
//
// {"channel":"webDevelopment","msg":"msg to the server"}
closeObserver allows us to set a custom error when an error raise up.
```

```javascript
import { webSocket } from "rxjs/webSocket";

const wsSubject = webSocket({
  url: "ws://localhost:8081",
  closeObserver: {
    next(closeEvent) {
      const customError = { code: 6666, reason: "Custom evil reason" };
      console.log(`code: ${customError.code}, reason: ${customError.reason}`);
    },
  },
});

//output
// code: 6666, reason: Custom evil reason
```

openObserver, Let's say we need to make some kind of init task before sending/receiving msgs to the webSocket or sending notification that the connection was successful, this is when openObserver is usefull for.

```javascript
import { webSocket } from "rxjs/webSocket";

const wsSubject = webSocket({
  url: "ws://localhost:8081",
  openObserver: {
    next: () => {
      console.log("Conexión OK");
    },
  },
});

// Salida:
// Conexión OK`
```

## Propiedades

| Propiedad       | Tipo                                                                | Descripción                                                                                                                                                                                                            |
| --------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| url             | `string`                                                            | La url del servidor al que conectarse.                                                                                                                                                                                 |
| protocol        | `string \| Array`                                                   | El protocolo a utilizar para conectar.                                                                                                                                                                                 |
| resultSelector  | `(e: MessageEvent) => T`                                            |                                                                                                                                                                                                                        |
| serializer      | `(value: T) => WebSocketMessage`                                    | El serializador utilizado para crear mensajes a partir de los valores proporcionados antes de que los mensajes se envían al servidor. Por defecto es `JSON.stringify`                                                  |
| deserializer    | `(e: MessageEvent) => T`                                            | El deserialiador utilizado para los mensajes que llegan al socket desde el servidor. Por defecto es `JSON.parse`                                                                                                       |
| openObserver    | `NextObserver`                                                      | Un Observador que observa los eventos *open* que ocurran en el webSocket subyacente.                                                                                                                                   |
| closeObserver   | `NextObserver`                                                      | Un Observador que observa los eventos *close* que ocurran en el webSocket subyacente.                                                                                                                                  |
| closingObserver | `NextObserver`                                                      | Un Observador que observa el momento en el que un evnto *close* va a ocurrir debido a una cancelación de suscripción.                                                                                                  |
| WebSocketCtor   | `{ new (url: string, protocols?: string \| string[]): WebSocket; }` | El constructor WebSocket que utilizar. Esto puede resultar útil para utilizar una implementación de WebSocket en Node (WebSocket es una API del DOM) o para falsificar *(mock)* un WebSocket en un entorno de testing. |
| binaryType      | `'blob' \| 'arraybuffer'`                                           | Especifica la propiedad `binaryType` del WebSocket subyacente.                                                                                                                                                         |

## Recursos adicionales

[![Source code](https://github.com/puntotech/rxjs-docu/blob/master/doc/api/webSocket/assets/icons/source-code.png)](https://github.com/ReactiveX/rxjs/blob/6.5.5/src/internal/observable/dom/WebSocketSubject.ts#L8-L138)

[Documentación oficial en inglés](https://rxjs.dev/api/webSocket/WebSocketSubjectConfig)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://www.rxjs.es/api/websocket/websocketsubjectconfig.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
