未加星标

Communicate With Websockets In A NativeScript Angular Application

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

I’ve been playing around with sockets and websockets recently. Not too long ago I wrote about creating a real-time chat applicationusing Golang and Angular that made use of websockets. In that example we created a chat server using the Go programming language and a client facing web application using Angular. The communication between the two used websockets to keep things real-time.

What if we wanted to create a native mobile application for Android and iOS that communicated via websockets to our server or any other websocket server? Using NativeScript , it is very possible to create a mobile client that works with the Golang with Angular example as seen previously.

The example we’re going to see is a simple chat application. The Android and iOS application will connect to a server using websockets and communicate to it in real-time.


Communicate With Websockets In A NativeScript Angular Application

The focus of this example will not be creating a websocket server, but instead a NativeScript websocket client. If you want a working and easy to use Golang websocket server, check out myprevious article on the topic.

Creating a NativeScript Project with Websockets

To make the NativeScript application easy to understand, we’re going to start with a fresh project. With NativeScript installed, execute the following using the CLI:

tnscreateWebsocketProject --ng cd WebsocketProject tnsplatformaddios tnsplatformaddandroid

In the above commands, we’re creating an Angular with TypeScript project by making use of the --ng tag. While we’re adding the iOS build platform, we can’t actually build for iOS unless we’re using a Mac with Xcode installed.

Because NativeScript applications are native applications and not web applications, the concept of websockets don’t quite exist. To make this possible, we need to install the nifty nativescript-websockets plugin by Nathanael Anderson. To do this, execute the following within your project:

tnspluginaddnativescript-websockets

At this point the application is created and ready to use websocket communications.

Adding the Angular and TypeScript Logic

For simplicity, this chat application will only be a single page application. This means all of our logic will reside in a single file. Open the project’s app/app.component.ts file and include the following TypeScript code:

import { Component, OnInit, OnDestroy, NgZone } from "@angular/core"; require("nativescript-websockets"); @Component({ selector: "my-app", templateUrl: "app.component.html", }) exportclass AppComponentimplements OnInit, OnDestroy { privatesocket: any; publicmessages: Array<any>; publicchatBox: string; public constructor(privatezone: NgZone) { this.socket = new WebSocket("ws://192.168.57.1:12345/ws", []); this.messages = []; this.chatBox = ""; } public ngOnInit() { this.socket.addEventListener('open', event => { this.zone.run(() => { this.messages.push({content: "Welcome to the chat!"}); }); }); this.socket.addEventListener('message', event => { this.zone.run(() => { this.messages.push(JSON.parse(event.data)); }); }); this.socket.addEventListener('close', event => { this.zone.run(() => { this.messages.push({content: "You have been disconnected"}); }); }); this.socket.addEventListener('error', event => { console.log("The socket had an error", event.error); }); } public ngOnDestroy() { this.socket.close(); } public send() { if(this.chatBox) { this.socket.send(this.chatBox); this.chatBox = ""; } } }

There is a lot going on in the above so we’re going to break it down.

We need to first import a few Angular components as well as the websocket plugin:

import { Component, OnInit, OnDestroy, NgZone } from "@angular/core"; require("nativescript-websockets");

The websocket listeners will start in the ngOnInit which is part of the OnInit interface. The socket will be gracefully destroyed in the ngOnDestroy which is part of OnDestroy . Listeners with Angular UIs tend to be a little wonky so we need to use NgZone for updating the UI within a listen event.

Inside the AppComponent class we have a few public and private variables:

privatesocket: any; publicmessages: Array<any>; publicchatBox: string;

The socket variable will hold our websocket while messages will hold all chat messages that will be bound to the UI. The chatBox variable is bound to a form within the UI.

Inside the constructor method we can initialize our variables and establish a connection to the server via websockets:

public constructor(privatezone: NgZone) { this.socket = new WebSocket("ws://192.168.57.1:12345/ws", []); this.messages = []; this.chatBox = ""; }

The websocket address is that of which I created in the Golang example. You can simply replace the address with that of your actual websocket server.

The ngOnInit method is where all the magic happens:

public ngOnInit() { this.socket.addEventListener('open', event => { this.zone.run(() => { this.messages.push({content: "Welcome to the chat!"}); }); }); this.socket.addEventListener('message', event => { this.zone.run(() => { this.messages.push(JSON.parse(event.data)); }); }); this.socket.addEventListener('close', event => { this.zone.run(() => { this.messages.push({content: "You have been disconnected"}); }); }); this.socket.addEventListener('error', event => { console.log("The socket had an error", event.error); }); }

With websockets there are four possible events. When the connection is established, when a data load or message was received, when the socket connection was closed, and when there was an error. Any time we need to present something on the screen, we wrap it in a zone.run and everything will be great.

To avoid confusion, the data we’re expecting is based once again on the Golang application that I’ve been mentioning. In that application, the data payload is JSON in the following format:

{ "sender": string, "content": string, "recipient": string, "timestamp": string }

With the format known, we can see that we’re parsing it into a JSON object.

When it comes to actually sending data to the other end, we have our send method:

public send() { if(this.chatBox) { this.socket.send(this.chatBox); this.chatBox = ""; } }

If the form is not empty, send the content to the socket and clear the form. Depending on if the server relays the message back to the client, the message listener might trigger.

Because data will be bound to forms within the UI, a certain Angular module must be imported. Open the project’s app/ap

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: iOSWebSocketAndroid
分页:12
转载请注明
本文标题:Communicate With Websockets In A NativeScript Angular Application
本站链接:http://www.codesec.net/view/522336.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(65)