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

fix: add socket keepalive #205

Merged
merged 3 commits into from
Sep 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export class TCP implements Transport {

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

// Avoid uncaught errors caused by unstable connections
socket.on('error', err => {
Expand Down
2 changes: 2 additions & 0 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export function createListener (context: Context) {
let listeningAddr: Multiaddr

const server: ServerWithMultiaddrConnections = Object.assign(net.createServer(socket => {
socket.setKeepAlive(true)

// Avoid uncaught errors caused by unstable connections
socket.on('error', err => {
log('socket error', err)
Expand Down
15 changes: 14 additions & 1 deletion src/socket-to-conn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,20 @@ export const toMultiaddrConnection = (socket: Socket, options?: ToConnectionOpti
options.localAddr = options.remoteAddr
}

const remoteAddr = options.remoteAddr ?? toMultiaddr(socket.remoteAddress ?? '', socket.remotePort ?? '')
let remoteAddr: Multiaddr

if (options.remoteAddr != null) {
remoteAddr = options.remoteAddr
} else {
if (socket.remoteAddress == null || socket.remotePort == null) {
// this can be undefined if the socket is destroyed (for example, if the client disconnected)
// https://nodejs.org/dist/latest-v16.x/docs/api/net.html#socketremoteaddress
throw errCode(new Error('Could not determine remote address or port'), 'ERR_NO_REMOTE_ADDRESS')
}

remoteAddr = toMultiaddr(socket.remoteAddress, socket.remotePort)
}

const { host, port } = remoteAddr.toOptions()
const { sink, source } = toIterable.duplex(socket)

Expand Down