Skip to content
This repository was archived by the owner on Aug 29, 2023. It is now read-only.

Commit 9ac799b

Browse files
authored
fix: add socket keepalive (#205)
* fix: add socket keepalive This is consistent with go-libp2p for [incoming](https://github.com/libp2p/go-libp2p/blob/master/p2p/transport/tcp/tcp.go#L85) and [outgoing](https://github.com/libp2p/go-libp2p/blob/master/p2p/transport/tcp/tcp.go#L191) connections * chore: fix remote address * chore: handle missing details
1 parent 50590c6 commit 9ac799b

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export class TCP implements Transport {
4949

5050
async dial (ma: Multiaddr, options: DialOptions): Promise<Connection> {
5151
const socket = await this._connect(ma, options)
52+
socket.setKeepAlive(true)
5253

5354
// Avoid uncaught errors caused by unstable connections
5455
socket.on('error', err => {

src/listener.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ export function createListener (context: Context) {
4848
let listeningAddr: Multiaddr
4949

5050
const server: ServerWithMultiaddrConnections = Object.assign(net.createServer(socket => {
51+
socket.setKeepAlive(true)
52+
5153
// Avoid uncaught errors caused by unstable connections
5254
socket.on('error', err => {
5355
log('socket error', err)

src/socket-to-conn.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,20 @@ export const toMultiaddrConnection = (socket: Socket, options?: ToConnectionOpti
3838
options.localAddr = options.remoteAddr
3939
}
4040

41-
const remoteAddr = options.remoteAddr ?? toMultiaddr(socket.remoteAddress ?? '', socket.remotePort ?? '')
41+
let remoteAddr: Multiaddr
42+
43+
if (options.remoteAddr != null) {
44+
remoteAddr = options.remoteAddr
45+
} else {
46+
if (socket.remoteAddress == null || socket.remotePort == null) {
47+
// this can be undefined if the socket is destroyed (for example, if the client disconnected)
48+
// https://nodejs.org/dist/latest-v16.x/docs/api/net.html#socketremoteaddress
49+
throw errCode(new Error('Could not determine remote address or port'), 'ERR_NO_REMOTE_ADDRESS')
50+
}
51+
52+
remoteAddr = toMultiaddr(socket.remoteAddress, socket.remotePort)
53+
}
54+
4255
const { host, port } = remoteAddr.toOptions()
4356
const { sink, source } = toIterable.duplex(socket)
4457

0 commit comments

Comments
 (0)