TCP socket for use with "LensStudio:Network".TcpSocket.

import * as Network from "LensStudio:Network"

export default class TcpServerManager {
constructor() {
this.server = Network.TcpServer.create()
this.connections = []
this.sockets = []
this.onClientConnected = null
this.onClientDataReceived = null
this.onClientDisconnected = null
this.onClientSocketError = null
this.enableLogging = false

// Setup listeners
this.connections.push(
this.server.onConnect.connect(socket => {
//save sockets to the persistent array so they dont get garbage collected
this.sockets.push(socket)

if (this.enableLogging) {
Editor.print(`Incoming connection from ${socket.remoteAddress.address}:${socket.remoteAddress.port}`)
}

if (this.onClientConnected) {
this.onClientConnected(socket)
}

this.connections.push(
socket.onData.connect(data => {
if (this.enableLogging) {
Editor.print(`Received data from socket: ${data}`)
}

if (this.onClientDataReceived) {
this.onClientDataReceived(data, socket)
}
})
)

this.connections.push(
socket.onEnd.connect(() => {
if (this.enableLogging) {
Editor.print(`Socket connected to ${socket.remoteAddress.address}:${socket.remoteAddress.port} disconnected from the server.`)
}

if (this.onClientDisconnected) {
this.onClientDisconnected(socket)
}
})
)

this.connections.push(
socket.onError.connect(error => {
if (this.enableLogging) {
logger.logException(`Socket error: ${error}`)
}

if (this.onClientSocketError) {
this.onClientSocketError(error, socket)
}
})
)
})
)
}

start (address, port) {
const localhostAddr = new Network.Address()
localhostAddr.address = address
localhostAddr.port = port
try {
this.server.listen(localhostAddr)
Editor.print(`Server started at ${address}:${port}`)
} catch (e) {
Editor.print("Failed to start the server: " + e)
}
}

close (){
// Disconnect all the connections
this.connections.forEach(connection => connection.disconnect())
this.connections = []
// Close the server
this.server.close()
}
}
interface TcpSocket {
    localAddress: Address;
    onData: signal1<Buffer, void>;
    onEnd: signal0<void>;
    onError: signal1<number, void>;
    remoteAddress: Address;
    close(): void;
    destroy(): void;
    getTypeName(): string;
    isOfType(type: string): boolean;
    isSame(other: ScriptObject): boolean;
    write(data: string | Uint8Array): number;
}

Hierarchy (view full)

Properties

localAddress: Address
onData: signal1<Buffer, void>
onEnd: signal0<void>
onError: signal1<number, void>
remoteAddress: Address

Methods

  • Parameters

    • type: string

    Returns boolean

  • Write to the socket.

    Parameters

    • data: string | Uint8Array

    Returns number