Skip to content
This repository was 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 1 commit
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
12 changes: 11 additions & 1 deletion src/socket-to-conn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,17 @@ 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 {
const address = socket.address()

// @ts-expect-error type of address is `{} | AdressInfo` - how to exclude {}?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you can explicitly type address above.
const address: AddressInfo = ...

remoteAddr = toMultiaddr(address.address ?? '0.0.0.0', address.port ?? 0)
}

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

Expand Down