Ionic 2 Chat

Hi All,

I am trying to create a chat app.

I have a Java Server and Ionic 2 Client.

I get the following error:

ORIGINAL EXCEPTION: ReferenceError: io is not defined

Any suggestions please?

Thanks


I have the following code so far:

CLIENT
ts

import { Component, NgZone } from '@angular/core';
import { Http } from "@angular/http";
declare var io;
//require ('io');
@Component({
  templateUrl: 'build/pages/chat/chat.html',
})
export class ChatPage {
  private socketHost: string = "http://localhost:3700";
  private messages: string[] = [];
  private zone: NgZone = null;
  private chatBox: string = null;
  private socket: any = null;
  constructor(http: Http) {
    this.messages = [];
    this.zone = new NgZone({ enableLongStackTrace: false });
    //let url = this.socketHost + "/fetch";
    let url = this.socketHost;
    http.get(url).subscribe((success) => {
      var data = success.json();
      for (var i = 0; i < data.length; i++) {
        this.messages.push(data[i].message);
      }
    }, (error) => {
      console.log(JSON.stringify(error));
    });
    this.chatBox = "";
    this.socket = io(this.socketHost);
    this.socket.on("chat_message", (msg) => {
      this.zone.run(() => {
        this.messages.push(msg);
      });
    });
  }
  send(message) {
    if (message && message != "") {
      this.socket.emit("chat_message", message);
    }
    this.chatBox = "";
  }
}

html

<ion-navbar *navbar>
    <ion-title>
        Chat
    </ion-title>
</ion-navbar>
 
<ion-content class="home">
    <ion-list>
        <ion-item *ngFor="let message of messages">{{message}}</ion-item>
    </ion-list>
</ion-content>
 
<ion-footer-bar>
    <ion-input>
        <input type="text" [(ngModel)]="chatBox" placeholder="Message..." />
        <button (click)="send(chatBox)">Send</button>
    </ion-input>
</ion-footer-bar>

index.html

<script src="/socket.io/socket.io.js"></script>

SERVER
Java

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
 
public class Server {
 
    public static void main(String[] args) {
        Configuration config = new Configuration();
        config.setHostname("localhost");
        config.setPort(3700);
        final SocketIOServer server = new SocketIOServer(config);
        server.addConnectListener(new ConnectListener() {
            @Override
            public void onConnect(SocketIOClient client) {
                System.out.println("onConnected");
                client.sendEvent("message", new Message("", "Welcome to the chat!"));
            }
        });
        server.addDisconnectListener(new DisconnectListener() {
            @Override
            public void onDisconnect(SocketIOClient client) {
                System.out.println("onDisconnected");
            }
        });
        server.addEventListener("send", Message.class, new DataListener<Message>() {
 
            @Override
            public void onData(SocketIOClient client, Message data, AckRequest ackSender) throws Exception {
                System.out.println("onSend: " + data.toString());
                server.getBroadcastOperations().sendEvent("message", data);
            }
        });
        System.out.println("Starting server...");
        server.start();
        System.out.println("Server started");
 
    }
}

I add the following to index.html, and I don’t get any errors any more:

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

But it just hangs. And in Firebug, I can see that the following request is just hanging:

GET http://localhost:3700/

The following is printed in the server console:

onConnected

When the server is not running the following request times out as expected, but when the server is running, the request does return, but with a null response:

GET http://localhost:3700/socket.io/?EIO=3&transport=...LRQn9sx&sid=53081e79-81f3-4fc0-8fb7-17c8673938ca
200 OK
27ms

So it suggests that my server code or the communication between client and server is wrong I think.

Any ideas?

So you’re using socket.io?

Try this

npm install socket.io --save
typings install dt~socket.io --global --save

Then in your class, you can do

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as sio from 'socket.io';
@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  public server = sio();
  constructor(public navCtrl: NavController) {
    this.server.on('connection',(socket)=> {
      console.log('User ' + socket.id + ' connected');
    });
  }
}

@mhartington: I wanted to try your piece of code with Ionic 3 and I always get this error - gotta a solution for this issue?

Runtime Error
Uncaught (in promise): TypeError: exists is not a function TypeError: exists is not a function at resolvePath (http://xxx/build/vendor.js:139706:9) at Server.serveClient (http://xxx/build/vendor.js:139712:25) at new Server (http://xxx/build/vendor.js:139651:8) at Server (http://xxx/build/vendor.js:139643:41) at new HomePage (http://xxx/build/main.js:61:23) at createClass (http://xxx/build/vendor.js:12516:20) at createDirectiveInstance (http://xxx/build/vendor.js:12363:37) at createViewNodes (http://xxx/build/vendor.js:13801:53) at createRootView (http://xxx/build/vendor.js:13691:5) at callWithDebugContext (http://xxx/build/vendor.js:15092:42)

Thnaks in advance!