npm i --save nativescript-simple-networking
- 版本:0.1.1
- GitHub: https://github.com/yaqwsx/nativescript-simple-networking
- NPM: https://npmjs.net.cn/package/nativescript-simple-networking
- 下载
- 昨天:0
- 上周:0
- 上个月:0
NativeScript Simple Networking
为 NativeScript 提供基本的 UDP 和 TCP 套接字。
支持的平台
- Android(任何运行 Android 4.4 及以上版本的设备)
由于我不是 iOS 开发者,目前不支持 iOS。欢迎为添加 iOS 支持做出贡献!
安装
tns plugin add nativescript-simple-networking
使用方法
此插件提供了三个类:UdpServer
、TcpClient
和 TcpServer
。它们都提供了类似的基于回调的接口。使用示例胜过千言万语,因此这里提供一个 TypeScript 示例
import {UdpServer, TcpClient, TcpServer} from "nativescript-simple-networking";
import {Address4} from "ip-address";
var udpServer = new UdpServer();
udpServer.onPacket = (sender: Address4, message: string) => {
console.log("Message from UDP: ", message);
};
udpServer.onError = (id: number, message: string) => {
console.log("UDP error for action #", id, ": ", message);
};
udpServer.onFinished = (id: number) => {
console.log("UDP finished action #", id);
};
// Start listening on port 33333
var udpConnectEvent: number = udpServer.start(33333);
console.log("UDP start event is: ", udpConnectEvent);
// Broadcast a message
var udpBroadcastEvent: number = udpServer.send("255.255.255.255", "I am alive!");
console.log("UDP broadcast event is: ", udpBroadcastEvent);
// Start a TCP server listening on port 44444 with maximum 2 clients
var tcpServer = new TcpServer(2);
tcpServer.onClient = (client: Address4) => {
console.log("New TCP client: ", client.adddress)
tcpServer.send(client, "Welcome!");
};
tcpServer.onData = (client: Address4, data: string) => {
console.log("New data from client ", client.address, ": ", data);
};
tcpServer.onError = (id: number, client: Address4, message: string) => {
if (client)
console.log("TCP server client error", client.address, ": ", message);
else
console.log("TCP server error: ", message);
};
tcpServer.onFinished = (id: number) => {
console.log("TCP server finished transaction #", id);
};
tcpServer.start(44444);
// Connect to the TCP server
var tcpClient = new TcpClient();
tcpClient.onData = (data: string) => {
console.log("Data from TCP client: ", data);
};
tcpClient.onError = (id: number, message: string) => {
console.log("TCP client error for action #", id, ": ", message);
};
tcpClient.onFinished = (id: number) => {
console.log("TCP client finished action #: ", id);
};
// Connect client, action IDs are ommited in this example - see UdpServer
tcpClient.start("localhost", 44444);
tcpClient.send("I am also alive!");
// When we are finished
udpServer.stop();
TcpServer.stop();
TcpClient.stop();
贡献
欢迎任何形式的贡献,请在 GitHub 上提交拉取请求。我会非常感激添加 iOS 支持的 PR。
未来计划
- 支持 iOS
- 实现基于未来的接口包装器