├── .npmignore
├── SimpleNetworking
├── library
│ ├── .gitignore
│ ├── src
│ │ ├── main
│ │ │ ├── res
│ │ │ │ └── values
│ │ │ │ │ ├── strings.xml
│ │ │ │ │ ├── colors.xml
│ │ │ │ │ └── styles.xml
│ │ │ ├── AndroidManifest.xml
│ │ │ └── java
│ │ │ │ └── cz
│ │ │ │ └── honzamrazek
│ │ │ │ └── simplenetworking
│ │ │ │ ├── TcpClientListener.java
│ │ │ │ ├── UdpListener.java
│ │ │ │ ├── TcpServerListener.java
│ │ │ │ ├── TcpClient.java
│ │ │ │ ├── UdpServer.java
│ │ │ │ └── TcpServer.java
│ │ ├── test
│ │ │ └── java
│ │ │ │ └── cz
│ │ │ │ └── honzamrazek
│ │ │ │ └── simplenetworking
│ │ │ │ └── ExampleUnitTest.java
│ │ └── androidTest
│ │ │ └── java
│ │ │ └── cz
│ │ │ └── honzamrazek
│ │ │ └── simplenetworking
│ │ │ └── ExampleInstrumentedTest.java
│ ├── build.gradle
│ └── proguard-rules.pro
├── settings.gradle
├── .idea
│ ├── copyright
│ │ └── profiles_settings.xml
│ ├── modules.xml
│ ├── gradle.xml
│ ├── compiler.xml
│ └── misc.xml
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── .gitignore
├── build.gradle
├── gradle.properties
├── gradlew.bat
└── gradlew
├── index.d.ts
├── .gitignore
├── references.d.ts
├── platforms
└── android
│ ├── libs
│ └── SimpleNetworking.aar
│ └── AndroidManifest.xml
├── Makefile
├── tsconfig.json
├── LICENSE
├── package.json
├── index.ios.ts
├── README.md
└── index.android.ts
/.npmignore:
--------------------------------------------------------------------------------
1 | SimpleNetworking
2 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/index.d.ts:
--------------------------------------------------------------------------------
1 | export * from "./index.android";
2 |
--------------------------------------------------------------------------------
/SimpleNetworking/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':library'
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.js
2 | *.map
3 | index.*.d.ts
4 | node_modules
5 |
--------------------------------------------------------------------------------
/references.d.ts:
--------------------------------------------------------------------------------
1 | ///
--------------------------------------------------------------------------------
/SimpleNetworking/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SimpleNetworking
3 |
4 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/platforms/android/libs/SimpleNetworking.aar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yaqwsx/nativescript-simple-networking/HEAD/platforms/android/libs/SimpleNetworking.aar
--------------------------------------------------------------------------------
/SimpleNetworking/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yaqwsx/nativescript-simple-networking/HEAD/SimpleNetworking/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/SimpleNetworking/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | all: lib
2 |
3 | java_build:
4 | cd SimpleNetworking && gradle build
5 |
6 | lib: java_build
7 | cp SimpleNetworking/library/build/outputs/aar/library-release.aar platforms/android/libs/SimpleNetworking.aar
8 |
--------------------------------------------------------------------------------
/platforms/android/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/java/cz/honzamrazek/simplenetworking/TcpClientListener.java:
--------------------------------------------------------------------------------
1 | package cz.honzamrazek.simplenetworking;
2 |
3 | public interface TcpClientListener {
4 | void onData(String data);
5 | void onError(int id, String message);
6 | void onFinished(int id);
7 | }
8 |
--------------------------------------------------------------------------------
/SimpleNetworking/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Mar 19 22:58:23 CET 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/java/cz/honzamrazek/simplenetworking/UdpListener.java:
--------------------------------------------------------------------------------
1 | package cz.honzamrazek.simplenetworking;
2 |
3 | import java.net.InetAddress;
4 |
5 | public interface UdpListener {
6 | void onPacket(InetAddress sender, String data);
7 | void onFinished(int id);
8 | void onError(int id, String message);
9 | }
10 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/java/cz/honzamrazek/simplenetworking/TcpServerListener.java:
--------------------------------------------------------------------------------
1 | package cz.honzamrazek.simplenetworking;
2 |
3 | import java.net.InetAddress;
4 |
5 | public interface TcpServerListener {
6 | void onClient(InetAddress client);
7 | void onData(InetAddress client, String data);
8 | void onError(int id, InetAddress client, String message);
9 | void onFinished(int id);
10 | }
11 |
--------------------------------------------------------------------------------
/SimpleNetworking/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/test/java/cz/honzamrazek/simplenetworking/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package cz.honzamrazek.simplenetworking;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/SimpleNetworking/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.0'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/SimpleNetworking/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
17 |
18 |
--------------------------------------------------------------------------------
/SimpleNetworking/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/SimpleNetworking/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "declaration": true,
6 | "removeComments": true,
7 | "noLib": false,
8 | "emitDecoratorMetadata": true,
9 | "experimentalDecorators": true,
10 | "sourceMap": true,
11 | "pretty": true,
12 | "allowUnreachableCode": false,
13 | "allowUnusedLabels": false,
14 | "noEmitHelpers": true,
15 | "noEmitOnError": false,
16 | "noImplicitAny": false,
17 | "noImplicitReturns": true,
18 | "noImplicitUseStrict": false,
19 | "noFallthroughCasesInSwitch": true,
20 | "typeRoots": [
21 | "./node_modules/@types",
22 | "./node_modules"
23 | ],
24 | "types": [
25 | ]
26 | },
27 | "compileOnSave": false
28 | }
29 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/androidTest/java/cz/honzamrazek/simplenetworking/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package cz.honzamrazek.simplenetworking;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("cz.honzamrazek.simplenetworking", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 | defaultConfig {
7 | minSdkVersion 15
8 | targetSdkVersion 25
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | compile fileTree(dir: 'libs', include: ['*.jar'])
23 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
24 | exclude group: 'com.android.support', module: 'support-annotations'
25 | })
26 | compile 'com.android.support:appcompat-v7:25.3.0'
27 | compile 'com.android.support.constraint:constraint-layout:1.0.1'
28 | testCompile 'junit:junit:4.12'
29 | }
30 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/xmrazek7/Android/Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Jan Mrázek
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "nativescript-simple-networking",
3 | "version": "0.1.0",
4 | "description": "UDP and TCP sockets for NativeScript",
5 | "keywords": [
6 | "UDP",
7 | "TCP",
8 | "socket",
9 | "network",
10 | "nativescript",
11 | "javascript"
12 | ],
13 | "repository": {
14 | "type": "git",
15 | "url": "https://github.com/yaqwsx/nativescript-simple-networking.git"
16 | },
17 | "author": {
18 | "name": "Jan Mrázek",
19 | "email": "email@honzamrazek.cz",
20 | "url": "https://honzamrazek.cz"
21 | },
22 | "bugs": {
23 | "url": "https://github.com/yaqwsx/nativescript-simple-networking/issues"
24 | },
25 | "license": {
26 | "type": "MIT",
27 | "url": "https://github.com/yaqwsx/nativescript-simple-networking/blob/master/LICENSE"
28 | },
29 | "homepage": "https://github.com/yaqwsx/nativescript-simple-networking",
30 | "readmeFilename": "README.md",
31 | "main": "index",
32 | "typyings": "index.d.ts",
33 | "scripts": {
34 | "prepublish": "tsc"
35 | },
36 | "nativescript": {
37 | "platforms": {
38 | "android": "2.4.0"
39 | }
40 | },
41 | "devDependencies": {
42 | "typescript": "^2.2.1"
43 | },
44 | "dependencies": {
45 | "ip-address": "^5.8.6",
46 | "tns-platform-declarations": "^2.5.0",
47 | "util": "^0.10.3"
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/index.ios.ts:
--------------------------------------------------------------------------------
1 | import {Address4} from "ip-address";
2 |
3 | export class UdpServer {
4 | public onPacket: {(sender: Address4, packet: string): void;};
5 | public onError: {(id: number, message: string): void;};
6 | public onFinished: {(id: number): void;};
7 |
8 | public start(port: number): number {
9 | throw "Not implemented";
10 | }
11 |
12 | public stop(): number {
13 | throw "Not implemented";
14 | }
15 |
16 | public send(address: Address4, packet: string): number;
17 | public send(address: string, packet: string): number;
18 | public send(address: any, packet: string): number {
19 | throw "Not implemented";
20 | }
21 |
22 | public getNativeSocket(): java.net.DatagramSocket {
23 | throw "Not implemented";
24 | }
25 | }
26 |
27 | export class TcpClient {
28 | public onData: {(data: string): void;};
29 | public onError: {(id: number, message: string): void;};
30 | public onFinished: {(id: number): void;};
31 |
32 | public start(servername: string, port: number): number {
33 | throw "Not implemented"; }
34 |
35 | public stop(): number {
36 | throw "Not implemented";
37 | }
38 |
39 | public send(data: string): number {
40 | throw "Not implemented";
41 | }
42 | }
43 |
44 | export class TcpServer {
45 | public onClient: {(client: Address4): void;};
46 | public onData: {(client: Address4, data: string): void;};
47 | public onError: {(id: number, client: Address4, message: string): void;};
48 | public onFinished: {(id: number): void;};
49 |
50 | public start(port: number): number {
51 | throw "Not implemented";
52 | }
53 |
54 | public stop(): number {
55 | throw "Not implemented";
56 | }
57 |
58 | public send(client: Address4, data: string): number {
59 | throw "Not implemented";
60 | }
61 | }
62 |
63 |
--------------------------------------------------------------------------------
/SimpleNetworking/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/SimpleNetworking/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # NativeScript Simple Networking
2 |
3 | Basic UDP and TCP sockets for NativeScript.
4 |
5 | ## Supported platforms
6 |
7 | - Android (any device with Android 4.4 and higher)
8 |
9 | There is no support for iOS (yet), as I am not an iOS developer. Contributions
10 | for adding iOS support are welcome!
11 |
12 | ## Installing
13 |
14 | ```
15 | tns plugin add nativescript-simple-networking
16 | ```
17 |
18 | ## Usage
19 |
20 | This plugin provides three classes: `UdpServer`, `TcpClient` and `TcpServer`.
21 | All of them provide similar, callback-based, interface. An example of usage is
22 | worth a thousands words and therefore here is a TypeScript example:
23 |
24 | ```js
25 | import {UdpServer, TcpClient, TcpServer} from "nativescript-simple-networking";
26 | import {Address4} from "ip-address";
27 |
28 | var udpServer = new UdpServer();
29 | udpServer.onPacket = (sender: Address4, message: string) => {
30 | console.log("Message from UDP: ", message);
31 | };
32 | udpServer.onError = (id: number, message: string) => {
33 | console.log("UDP error for action #", id, ": ", message);
34 | };
35 | udpServer.onFinished = (id: number) => {
36 | console.log("UDP finished action #", id);
37 | };
38 |
39 | // Start listening on port 33333
40 | var udpConnectEvent: number = udpServer.start(33333);
41 | console.log("UDP start event is: ", udpConnectEvent);
42 | // Broadcast a message
43 | var udpBroadcastEvent: number = udpServer.send("255.255.255.255", "I am alive!");
44 | console.log("UDP broadcast event is: ", udpBroadcastEvent);
45 |
46 | // Start a TCP server listening on port 44444 with maximum 2 clients
47 | var tcpServer = new TcpServer(2);
48 | tcpServer.onClient = (client: Address4) => {
49 | console.log("New TCP client: ", client.adddress)
50 | tcpServer.send(client, "Welcome!");
51 | };
52 | tcpServer.onData = (client: Address4, data: string) => {
53 | console.log("New data from client ", client.address, ": ", data);
54 | };
55 | tcpServer.onError = (id: number, client: Address4, message: string) => {
56 | if (client)
57 | console.log("TCP server client error", client.address, ": ", message);
58 | else
59 | console.log("TCP server error: ", message);
60 | };
61 | tcpServer.onFinished = (id: number) => {
62 | console.log("TCP server finished transaction #", id);
63 | };
64 |
65 | tcpServer.start(44444);
66 |
67 | // Connect to the TCP server
68 | var tcpClient = new TcpClient();
69 | tcpClient.onData = (data: string) => {
70 | console.log("Data from TCP client: ", data);
71 | };
72 | tcpClient.onError = (id: number, message: string) => {
73 | console.log("TCP client error for action #", id, ": ", message);
74 | };
75 | tcpClient.onFinished = (id: number) => {
76 | console.log("TCP client finished action #: ", id);
77 | };
78 |
79 | // Connect client, action IDs are ommited in this example - see UdpServer
80 | tcpClient.start("localhost", 44444);
81 | tcpClient.send("I am also alive!");
82 |
83 | // When we are finished
84 | udpServer.stop();
85 | tcpServer.stop();
86 | tcpClient.stop();
87 | ```
88 |
89 | ## Contributing
90 |
91 | Any contributions are welcome, feel free to submit a pull request on GitHub. I
92 | would appreciate a PR, which would add support for iOS.
93 |
94 | ## Future Plans
95 |
96 | - support iOS
97 | - implement a wrapper for future-based interface
98 |
99 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/java/cz/honzamrazek/simplenetworking/TcpClient.java:
--------------------------------------------------------------------------------
1 | package cz.honzamrazek.simplenetworking;
2 |
3 | import java.io.IOException;
4 | import java.net.Socket;
5 | import java.util.Arrays;
6 | import java.util.concurrent.ExecutorService;
7 | import java.util.concurrent.Executors;
8 | import java.util.concurrent.atomic.AtomicInteger;
9 |
10 | public class TcpClient {
11 | private TcpClientListener mListener;
12 | private ExecutorService mExecutor;
13 | private Socket mSocket;
14 | private byte[] mBuffer;
15 | private AtomicInteger mId;
16 |
17 | TcpClient(Socket socket, AtomicInteger id, TcpClientListener listener) {
18 | mListener = listener;
19 | mSocket = socket;
20 | mId = id;
21 | mExecutor = Executors.newFixedThreadPool(2);
22 | mBuffer = new byte[8 * 1024 * 1024];
23 | receive();
24 | }
25 |
26 | public TcpClient(TcpClientListener listener) {
27 | mListener = listener;
28 | mExecutor = Executors.newFixedThreadPool(2);
29 | mBuffer = new byte[8 * 1024 * 1024];
30 | mId = new AtomicInteger();
31 | }
32 |
33 | Socket getNativeSocket() {
34 | return mSocket;
35 | }
36 |
37 | public int start(final String serverName, final int port) {
38 | final int id = mId.getAndIncrement();
39 | mExecutor.submit(new Runnable() {
40 | @Override
41 | public void run() {
42 | try {
43 | mSocket = new Socket(serverName, port);
44 | receive();
45 | mListener.onFinished(id);
46 | } catch (IOException e) {
47 | mListener.onError(id, e.getMessage());
48 | }
49 | }
50 | });
51 | return id;
52 | }
53 |
54 | public int stop() {
55 | final int id = mId.getAndIncrement();
56 | mExecutor.submit(new Runnable() {
57 | @Override
58 | public void run() {
59 | try {
60 | mSocket.close();
61 | mListener.onFinished(id);
62 | } catch (IOException e) {
63 | mListener.onError(id, e.getMessage());
64 | }
65 |
66 | }
67 | });
68 | return id;
69 | }
70 |
71 | public int send(final String data) {
72 | final int id = mId.getAndIncrement();
73 | mExecutor.submit(new Runnable() {
74 | @Override
75 | public void run() {
76 | try {
77 | mSocket.getOutputStream().write(data.getBytes());
78 | mListener.onFinished(id);
79 | } catch (IOException e) {
80 | mListener.onError(id, e.getMessage());
81 | }
82 | }
83 | });
84 | return id;
85 | }
86 |
87 | private void receive() {
88 | final int id = mId.getAndIncrement();
89 | mExecutor.submit(new Runnable() {
90 | @Override
91 | public void run() {
92 | try {
93 | int size = mSocket.getInputStream().read(mBuffer);
94 | byte [] sub = Arrays.copyOfRange(mBuffer, 0, size);
95 | String data = new String(sub);
96 | mListener.onData(data);
97 | } catch (IOException e) {
98 | mListener.onError(id, e.getMessage());
99 | }
100 | receive();
101 | }
102 | });
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/java/cz/honzamrazek/simplenetworking/UdpServer.java:
--------------------------------------------------------------------------------
1 | package cz.honzamrazek.simplenetworking;
2 |
3 | import android.util.Log;
4 |
5 | import java.io.IOException;
6 | import java.net.DatagramPacket;
7 | import java.net.DatagramSocket;
8 | import java.net.InetAddress;
9 | import java.net.SocketException;
10 | import java.nio.charset.Charset;
11 | import java.util.Arrays;
12 | import java.util.concurrent.ExecutorService;
13 | import java.util.concurrent.Executors;
14 | import java.util.concurrent.atomic.AtomicInteger;
15 |
16 | import cz.honzamrazek.simplenetworking.UdpListener;
17 |
18 | public class UdpServer {
19 | private UdpListener mListener;
20 | private ExecutorService mExecutor;
21 | private DatagramSocket mSocket;
22 | private AtomicInteger mId;
23 | private byte[] mBuffer;
24 |
25 | public UdpServer(UdpListener listener) {
26 | mListener = listener;
27 | mId = new AtomicInteger();
28 | }
29 |
30 | public DatagramSocket getNativeSocket() {
31 | return mSocket;
32 | }
33 |
34 | public int start(final int port) {
35 | final int id = mId.getAndIncrement();
36 | mBuffer = new byte[64 * 1024 * 1024];
37 | mExecutor = Executors.newFixedThreadPool(2);
38 | mExecutor.submit(new Runnable() {
39 | @Override
40 | public void run() {
41 | try {
42 | mSocket = new DatagramSocket(port);
43 | mExecutor.submit(new Runnable() {
44 | @Override
45 | public void run() {
46 | receiveDatagram();
47 | }
48 | });
49 | mListener.onFinished(id);
50 | }
51 | catch(SocketException e) {
52 | mListener.onError(id, e.getMessage());
53 | }
54 | }
55 | });
56 | return id;
57 | }
58 |
59 | public int stop() {
60 | final int id = mId.getAndIncrement();
61 | mExecutor.submit(new Runnable() {
62 | @Override
63 | public void run() {
64 | if (mSocket == null)
65 | return;
66 | mSocket.close();
67 | mSocket = null;
68 | mListener.onFinished(id);
69 | }
70 | });
71 | return id;
72 | }
73 |
74 | public int send(final InetAddress address, final String message) {
75 | final int id = mId.getAndIncrement();
76 | mExecutor.submit(new Runnable() {
77 | @Override
78 | public void run() {
79 | try {
80 | byte[] buffer = message.getBytes();
81 | DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
82 | address, mSocket.getLocalPort());
83 | mSocket.send(packet);
84 | mListener.onFinished(id);
85 | }
86 | catch(IOException e) {
87 | mListener.onError(id, e.getMessage());
88 | }
89 | }
90 | });
91 | return id;
92 | }
93 |
94 | private void receiveDatagram() {
95 | final int id = mId.getAndIncrement();
96 | mExecutor.submit(new Runnable() {
97 | @Override
98 | public void run() {
99 | try {
100 | DatagramPacket packet = new DatagramPacket(mBuffer, mBuffer.length);
101 | mSocket.receive(packet);
102 | byte [] sub = Arrays.copyOfRange(packet.getData(), 0, packet.getLength());
103 | String data = new String(sub);
104 | InetAddress address = packet.getAddress();
105 | mListener.onPacket(address, data);
106 | receiveDatagram();
107 | }
108 | catch (IOException e) {
109 | mListener.onError(id, e.getMessage());
110 | }
111 | }
112 | });
113 | }
114 | }
--------------------------------------------------------------------------------
/SimpleNetworking/library/src/main/java/cz/honzamrazek/simplenetworking/TcpServer.java:
--------------------------------------------------------------------------------
1 | package cz.honzamrazek.simplenetworking;
2 |
3 | import java.io.IOException;
4 | import java.net.InetAddress;
5 | import java.net.ServerSocket;
6 | import java.net.Socket;
7 | import java.util.concurrent.ConcurrentHashMap;
8 | import java.util.concurrent.ExecutorService;
9 | import java.util.concurrent.Executors;
10 | import java.util.concurrent.atomic.AtomicBoolean;
11 | import java.util.concurrent.atomic.AtomicInteger;
12 |
13 | public class TcpServer {
14 | private TcpServerListener mListener;
15 | private ExecutorService mExecutor;
16 | private ConcurrentHashMap mClients;
17 | private ServerSocket mServer;
18 | private int mMaxClients;
19 | private AtomicBoolean mIsAccepting;
20 | private AtomicInteger mId;
21 |
22 | public TcpServer(int maxClients, TcpServerListener listener) {
23 | mMaxClients = maxClients;
24 | mListener = listener;
25 | mExecutor = Executors.newFixedThreadPool(maxClients + 2);
26 | mClients = new ConcurrentHashMap<>();
27 | mIsAccepting = new AtomicBoolean(false);
28 | mId = new AtomicInteger();
29 | }
30 |
31 | ServerSocket getNativeSocket() {
32 | return mServer;
33 | }
34 |
35 | TcpClient getClient(InetAddress c) {
36 | return mClients.get(c);
37 | }
38 |
39 | public int start(final int port) {
40 | final int id = mId.getAndIncrement();
41 | mExecutor.submit(new Runnable() {
42 | @Override
43 | public void run() {
44 | try {
45 | mServer = new ServerSocket(port);
46 | mListener.onFinished(id);
47 | } catch (IOException e) {
48 | mListener.onError(id, null, e.getMessage());
49 | }
50 | accept();
51 | }
52 | });
53 | return id;
54 | }
55 |
56 | public int stop() {
57 | int id = mId.getAndIncrement();
58 | try {
59 | mServer.close();
60 | for (TcpClient c : mClients.values()) {
61 | c.stop();
62 | }
63 | mListener.onFinished(id);
64 | } catch (IOException e) {
65 | mListener.onError(id, null, e.getMessage());
66 | }
67 | return id;
68 | }
69 |
70 | public int send(final InetAddress client, final String data) {
71 | TcpClient c = mClients.get(client);
72 | if (c == null) {
73 | int id = mId.getAndIncrement();
74 | mListener.onError(id, client, "No such client");
75 | }
76 | return c.send(data);
77 | }
78 |
79 | private void accept() {
80 | final int id = mId.getAndIncrement();
81 | mExecutor.submit(new Runnable() {
82 | @Override
83 | public void run() {
84 | if (mIsAccepting.get() || mMaxClients == mClients.size())
85 | return;
86 | mIsAccepting.set(true);
87 | try {
88 | Socket s = mServer.accept();
89 | final InetAddress address = s.getInetAddress();
90 | TcpClient c = new TcpClient(s, mId, new TcpClientListener() {
91 | @Override
92 | public void onData(String data) {
93 | mListener.onData(address, data);
94 | }
95 |
96 | @Override
97 | public void onError(int id, String message) {
98 | mListener.onError(id, address, message);
99 | }
100 |
101 | @Override
102 | public void onFinished(int id) {
103 | mListener.onFinished(id);
104 | }
105 | });
106 | mClients.put(s.getInetAddress(), c);
107 | mListener.onClient(s.getInetAddress());
108 | } catch (IOException e) {
109 | mListener.onError(id, null, e.getMessage());
110 | } finally {
111 | mIsAccepting.set(false);
112 | }
113 | };
114 | });
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/SimpleNetworking/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/index.android.ts:
--------------------------------------------------------------------------------
1 | ///
2 | declare module cz {
3 | export module honzamrazek {
4 | export module simplenetworking {
5 | interface IUdpListener {
6 | onPacket(sender: java.net.InetAddress, packet: string): void;
7 | onFinished(id: number): void;
8 | onError(id: number, message: string): void;
9 | }
10 |
11 | export class UdpListener {
12 | constructor(implementation: IUdpListener);
13 | onPacket(sender: java.net.InetAddress, packet: string): void;
14 | onFinished(id: number): void;
15 | onError(id: number, message: string): void;
16 | }
17 |
18 | export class UdpServer {
19 | constructor(listener: cz.honzamrazek.simplenetworking.UdpListener);
20 | start(port: number): number;
21 | stop(): number;
22 | send(address: java.net.InetAddress, packet: string): number;
23 | getNativeSocket(): java.net.DatagramSocket;
24 | }
25 |
26 | interface ITcpClientListener {
27 | onData(data: string): void;
28 | onFinished(id: number): void;
29 | onError(id: number, message: string): void;
30 | }
31 |
32 | export class TcpClientListener {
33 | constructor(implementation: ITcpClientListener);
34 | onData(data: string): void;
35 | onFinished(id: number): void;
36 | onError(id: number, message: string): void;
37 | }
38 |
39 | export class TcpClient {
40 | constructor(listener: cz.honzamrazek.simplenetworking.TcpClientListener);
41 | start(serverName: string, port: number): number;
42 | stop(): number;
43 | send(data: string): number;
44 | getNativeSocket(): java.net.Socket;
45 | }
46 |
47 | interface ITcpServerListener {
48 | onClient(client: java.net.InetAddress): void;
49 | onData(client: java.net.InetAddress, data: string): void;
50 | onError(id: number, client: java.net.InetAddress, message: string): void;
51 | onFinished(id: number): void;
52 | }
53 |
54 | export class TcpServerListener {
55 | constructor(listener: cz.honzamrazek.simplenetworking.TcpServerListener);
56 | onClient(client: java.net.InetAddress): void;
57 | onData(client: java.net.InetAddress, data: string): void;
58 | onError(id: number, client: java.net.InetAddress, message: string): void;
59 | onFinished(id: number): void;
60 | }
61 |
62 | export class TcpServer {
63 | constructor(maxClients: number, listener: cz.honzamrazek.simplenetworking.TcpServerListener);
64 | start(port: number): number;
65 | stop(): number;
66 | send(client: java.net.InetAddress, data: string): number;
67 | getNativeSocket(): java.net.ServerSocket;
68 | getClient(client: java.net.InetAddress): cz.honzamrazek.simplenetworking.TcpClient;
69 | }
70 | }
71 | }
72 | }
73 |
74 | import {Address4} from "ip-address";
75 |
76 | export class UdpServer {
77 | private server: cz.honzamrazek.simplenetworking.UdpServer;
78 | public onPacket: {(sender: Address4, packet: string): void;};
79 | public onError: {(id: number, message: string): void;};
80 | public onFinished: {(id: number): void;};
81 |
82 | constructor() {
83 | var self = this;
84 | var listener = new cz.honzamrazek.simplenetworking.UdpListener({
85 | onPacket: (sender, packet) => {
86 | if (self.onPacket !== null)
87 | self.onPacket(new Address4(sender.getHostAddress()), packet);
88 | },
89 | onError: (id, message) => {
90 | if (self.onError !== null)
91 | self.onError(id, message);
92 | },
93 | onFinished: (id) => {
94 | if (self.onFinished !== null)
95 | self.onFinished(id);
96 | }
97 | });
98 | this.server = new cz.honzamrazek.simplenetworking.UdpServer(listener);
99 | }
100 |
101 | public start(port: number): number {
102 | return this.server.start(port);
103 | }
104 |
105 | public stop(): number {
106 | return this.server.stop();
107 | }
108 |
109 | public send(address: Address4, packet: string): number;
110 | public send(address: string, packet: string): number;
111 | public send(address: any, packet: string): number {
112 | var name: string;
113 | if (address && typeof address == "string")
114 | name = address;
115 | else
116 | name = address.address;
117 | return this.server.send(java.net.InetAddress.getByName(name), packet);
118 | }
119 |
120 | public getNativeSocket(): java.net.DatagramSocket {
121 | return this.server.getNativeSocket();
122 | }
123 | }
124 |
125 | export class TcpClient {
126 | private client: cz.honzamrazek.simplenetworking.TcpClient;
127 | public onData: {(data: string): void;};
128 | public onError: {(id: number, message: string): void;};
129 | public onFinished: {(id: number): void;};
130 |
131 | constructor() {
132 | var self = this;
133 | var listener = new cz.honzamrazek.simplenetworking.TcpClientListener({
134 | onData: (data) => {
135 | if (self.onData !== null)
136 | self.onData(data);
137 | },
138 | onError: (id, message) => {
139 | if (self.onError !== null)
140 | self.onError(id, message);
141 | },
142 | onFinished: (id) => {
143 | if (self.onFinished !== null)
144 | self.onFinished(id);
145 | }
146 | });
147 | this.client = new cz.honzamrazek.simplenetworking.TcpClient(listener);
148 | }
149 |
150 | public start(servername: string, port: number): number {
151 | return this.client.start(servername, port);
152 | }
153 |
154 | public stop(): number {
155 | return this.client.stop();
156 | }
157 |
158 | public send(data: string): number {
159 | return this.client.send(data);
160 | }
161 | }
162 |
163 | export class TcpServer {
164 | private server: cz.honzamrazek.simplenetworking.TcpServer;
165 | public onClient: {(client: Address4): void;};
166 | public onData: {(client: Address4, data: string): void;};
167 | public onError: {(id: number, client: Address4, message: string): void;};
168 | public onFinished: {(id: number): void;};
169 |
170 | constructor(maxClients: number) {
171 | var self = this;
172 | var listener = new cz.honzamrazek.simplenetworking.TcpServerListener({
173 | onClient: (client) => {
174 | if (self.onClient !== null)
175 | self.onClient(new Address4(client.getHostAddress()));
176 | },
177 | onData: (client, data) => {
178 | if (self.onData !== null)
179 | self.onData(new Address4(client.getHostAddress()), data);
180 | },
181 | onError: (id, client, message) => {
182 | if (self.onError !== null)
183 | self.onError(id, new Address4(client.getHostAddress()), message);
184 | },
185 | onFinished: (id) => {
186 | if (self.onFinished !== null)
187 | self.onFinished(id);
188 | }
189 | });
190 | this.server = new cz.honzamrazek.simplenetworking.TcpServer(maxClients, listener);
191 | }
192 |
193 | public start(port: number): number {
194 | return this.server.start(port);
195 | }
196 |
197 | public stop(): number {
198 | return this.server.stop();
199 | }
200 |
201 | public send(client: Address4, data: string): number {
202 | return this.server.send(java.net.InetAddress.getByName(client.address),
203 | data);
204 | }
205 | }
206 |
207 |
--------------------------------------------------------------------------------