# Socket.io
# Creating server
you can create new server or attach the socket server to exist server.
- create new:
```js
const Server = require('socket.io');
const io = new Server();
```
- attach to http server
```js
io.attach(server);
// OR
io.attach(3000) //PORT
```
- serve client????
- Cors origin
```js
io.origins(['https://foo.example.com:443']);
// OR add it in the options
const io = require('socket.io')(3000, {
origins: '*',
});
// OR using custom function
io.origins((origin, callback) => {
if (origin !== 'https://foo.example.com') {
return callback('origin not allowed', false);
}
callback(null, true);
});
```
- Namespace (used to emit events to group of users that uses that same Namespace)
```js
const chatNamespace = io.of('/chat');
chatNamespace.emmit("event", "to all chat users")
// --------- dynamic namespaces ---------
// client-side
const socket = io('/dynamic-101');
const dynamicNsp = io.of(/^\/dynamic-\d+$/).on('connect', (socket) => {
const newNamespace = socket.nsp; // newNamespace.name === '/dynamic-101'
// broadcast to all clients in the given sub-namespace
newNamespace.emit('hello');
});
```
- Rooms (like channels)
```js
//
namespace.in(room)
// ===
namespace.to(room)
const G7 = io.of('/GSG-G7');
oom) // namespace / server
G7.to('good-links').emit('event', { some: 'data' });
```
- get all users connected to (all || server || room)
```js
// io || io.of('/chat') || io.of('/chat').in("room")
io.of('/chat').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});
```
- set a middleware:
```js
io.use((socket, next) => {
if (socket.request.headers.cookie) return next();
next(new Error('Authentication error'));
});
```
## Events
- connect || connection
```js
// can be io for all || server || room
io.on('connect', (socket) => {
// ...
});
```
Examples
---
- [Book example](/s/book-example)
- [Slide example](/s/slide-example)
- [YAML metadata](/s/yaml-metadata)
- [Features](/s/features)
Themes
---
- [Dark theme](/theme-dark?both)
- [Vertical alignment](/theme-vertical-writing?both)
###### tags: `Templates` `Book`