2015-07-08 16:33:57 -07:00
ipfs-swarm Node.js implementation
=================================
2015-07-10 16:04:18 -07:00
[](http://ipn.io) [](http://ipfs.io/) [](http://webchat.freenode.net/?channels=%23ipfs)
2015-07-08 16:33:57 -07:00
> IPFS swarm implementation in Node.js
# Description
2015-07-09 15:45:03 -07:00
ipfs-swarm is an abstraction for the network layer on IPFS. It offers an API to open streams between peers on a specific protocol.
2015-07-21 16:00:59 -07:00
Ref spec (still a WiP) - https://github.com/diasdavid/specs/blob/protocol-spec/protocol/layers.md#network -layer
2015-07-09 15:45:03 -07:00
2015-07-08 16:33:57 -07:00
# Usage
2015-07-09 15:45:03 -07:00
2015-07-21 16:00:59 -07:00
### Create a new Swarm
2015-07-09 15:45:03 -07:00
2015-07-21 16:00:59 -07:00
```javascript
var Swarm = require('ipfs-swarm')
2015-07-10 12:28:40 -07:00
2015-07-21 16:00:59 -07:00
var s = new Swarm([port]) // `port` defalts to 4001
```
2015-07-10 12:28:40 -07:00
2015-07-21 16:00:59 -07:00
### Set the swarm to listen for incoming streams
```javascript
s.listen([port], [callback]) // `port` defaults to 4001, `callback` gets called when the socket starts listening
```
### Close the listener/socket and every open stream that was multiplexed on it
```javascript
s.closeListener()
```
### Register a protocol to be handled by an incoming stream
```javascript
s.registerHandler('/name/protocol/you/want/version', function (stream) {})
```
2015-07-25 18:42:36 -07:00
### Open a new connection
Used when we want to make sure we can connect to a given peer, but do not intend to establish a stream with any of the services offered right away.
```
s.openConnection(peerConnection, function (err) {})
```
2015-07-21 16:00:59 -07:00
### Dial a new stream
```
s.openStream(peerInfo, protocol, function (err, stream) {})
```
peerInfo must be a [`ipfs-peer` ](https://www.npmjs.com/package/ipfs-peer ) object, contaning both peer-id and multiaddrs.
## Events emitted
```
2015-07-10 12:28:40 -07:00
.on('error')
.on('connection')
2015-07-21 16:00:59 -07:00
.on('connection-unknown') // used by Identify to start the Identify protocol from listener to dialer
```
## Identify protocol
The Identify protocol is an integral part to Swarm. It enables peers to share observedAddrs, identities and other possible address available. This enables us to do better NAT traversal.
To instantiate Identify:
```
var Identify = require('ipfs-swarm/identify')
var i = new Identify(swarmInstance, peerSelf)
```
`swarmInstance` must be an Instance of swarm and `peerSelf` must be a instance of `ipfs-peer` that represents the peer that instantiated this Identify
2015-07-10 12:28:40 -07:00
2015-07-21 16:00:59 -07:00
Identify emits a `peer-update` event each time it receives information from another peer.