nkzawa / socket.io-android-chat Goto Github PK
View Code? Open in Web Editor NEWA simple chat demo for socket.io and Android
License: MIT License
A simple chat demo for socket.io and Android
License: MIT License
This code is error
import com.github.nkzawa.emitter.Emitter;
Please help me ..please fix this
my server use express4 and socket.io. use express when account login, register and so on. if user login success then this account use socket.io client login the chat....
but, I find the same client's session on server has two session id, one express, on socket.io.
android client use httpclient connect to express api. that socketcleint connect to socket.io.
so...sockectClient dosen't set cookie. I don't know to resolve!
This is my server
var app = require('http').createServer()
var io = require('socket.io')(app);
var fs = require('fs');
var init = function(port){
app.listen(port);
}
io.on('connection', function(socket){
console.log('connected');
socket.on('room_request', function(msg){
console.log(msg);
//room_index = msg;
for( i = 0; i < msg.length; i++)
{
socket.join(msg[i]);
console.log('channel created');
}
socket.on('disconnect', function(){
for( i = 0; i < msg.length; i++)
{
console.log('user disconnected');
socket.leave(msg[i]);
console.log('room closed');
}
});
});
});
var sendMessage = function(tId,message){
io.to(tId).emit('ping',message);
}
exports.sendMessage = sendMessage;
exports.init = init;
The init is called from another file.
The server works because I tried connecting to it from a simple html javascript app.
I downloaded the app and replaced the http://chat.socket.io with 'localhost:8089'(Thats the port on which the server is running).
I ran it on the simulator so the localhost would resolve to the same machine. But still the server is not hit.
Anything wrong that I am doing anywhere?
Not getting timeout event some times in call() Emitter.Listener. but its coming in Manager open() method in timeout
if (Manager.this._timeout >= 0) {
final long timeout = Manager.this._timeout;
logger.fine(String.format("connection attempt will timeout after %d", timeout));
final Future timer = getTimeoutScheduler().schedule(new Runnable() {
@Override
public void run() {
EventThread.exec(new Runnable() {
@Override
public void run() {
logger.fine(String.format("connect attempt timed out after %d", timeout));
openSub.destroy();
socket.close();
socket.emit(Engine.EVENT_ERROR, new SocketIOException("timeout"));
self.emitAll(EVENT_CONNECT_TIMEOUT, timeout);
}
});
}
}, timeout, TimeUnit.MILLISECONDS);
Manager.this.subs.add(new On.Handle() {
@Override
public void destroy() {
timer.cancel(false);
}
});
}
I tried to connect using this library and I'm also using okhttp for some api request but it has a conflict with okhttp dispatcher.
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: java.lang.NoSuchMethodError: com.squareup.okhttp.internal.Internal.callEngineGetConnection
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.ws.WebSocketCall.createWebSocket(WebSocketCall.java:154)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.ws.WebSocketCall.access$000(WebSocketCall.java:42)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.ws.WebSocketCall$1.onResponse(WebSocketCall.java:102)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:177)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-10 13:39:12.721 5216-5275/com.shima.thebizgames E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
Hi i'm trying to keep my application's service on background. But on close application. Connected socket not work. I dont have any close that on application normally and i'm using service instead intent service and using STICKY on start cimmand too. What hapen when i close app.socket dosconnected? Is there any solution to keep alive socket or service?
Hello
the application memory usage is about 5 megabytes
I want to use it for push purposes
is it possible to reduce memory usage ?
Hi,
We developed a chat application for android using socket.io library, But we are facing one issue.
When we kept app in background socket remains connected, even if we keep it idle for some time, socket doesn't disconnect which is fine, but the problem comes when we open any other app, socket disconnects.
Can you please tell us what can be the problem & solution for that.
Thanks in advance...
Hi,
While leaving the chat room the chat history is deleted how to store and show the chat history
how to add cookie?
Hi,
since I cannot join the chat.socket.io , I tried to use a simple java server sample to run this project. But it show these log when I emit login event:
2016-12-12 10:31:47.386 ERROR 582 --- [ntLoopGroup-3-4] c.c.socketio.JsonSupportWrapper : Can't read value: ["chatevent","{userName:gg}"] for type: class com.corundumstudio.socketio.protocol.Event
And I check the json android client submit , find out the source code wrapped everything with jsonarray as above and it cannot be mapped to a com.corundumstudio.socketio.protocol.Event class. Please help, how can I make it run?
BUILD SUCCESSFUL upon adding on dependencies
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'org.apache.commons:commons-lang3:3.1'
compile 'org.apache.commons:commons-collections4:4.0'
compile 'com.google.android.gms:play-services:6.1.+'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
compile 'com.facebook.android:facebook-android-sdk:3.23.1'
compile 'com.github.manuelpeinado.fadingactionbar:fadingactionbar:3.1.2'
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:+'
compile 'com.etsy.android.grid:library:1.0.5'
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
compile 'com.melnykov:floatingactionbutton:1.3.0'
compile('org.apache.httpcomponents:httpmime:4.3.6') {
exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
compile('com.twitter.sdk.android:twitter:1.8.0@aar') {
transitive = true;
}
compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
transitive = true;
}
compile 'io.socket:socket.io-client:0.6.1'
}
After I Run the app.I get this error...
Executing tasks: [:app:assembleDebug]
Configuration on demand is an incubating feature.
WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
In case of problem, please repackage with jarjar to change the class packages
WARNING: Dependency org.json:json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android.
In case of problem, please repackage with jarjar to change the class packages
WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
In case of problem, please repackage with jarjar to change the class packages
WARNING: Dependency org.json:json:20090211 is ignored for release as it may be conflicting with the internal version provided by Android.
In case of problem, please repackage with jarjar to change the class packages
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72103Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72103Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42301Library UP-TO-DATE
:app:prepareComAstuetzPagerslidingtabstrip101Library UP-TO-DATE
:app:prepareComCrashlyticsSdkAndroidAnswers132Library UP-TO-DATE
:app:prepareComCrashlyticsSdkAndroidBeta113Library UP-TO-DATE
:app:prepareComCrashlyticsSdkAndroidCrashlytics252Library UP-TO-DATE
:app:prepareComCrashlyticsSdkAndroidCrashlyticsCore235Library UP-TO-DATE
:app:prepareComDigitsSdkAndroidDigits180Library UP-TO-DATE
:app:prepareComEtsyAndroidGridLibrary105Library UP-TO-DATE
:app:prepareComFacebookAndroidFacebookAndroidSdk3231Library UP-TO-DATE
:app:prepareComGithubManuelpeinadoFadingactionbarFadingactionbar312Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServices6171Library UP-TO-DATE
:app:prepareComMelnykovFloatingactionbutton130Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTweetComposer090Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTweetUi150Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTwitter180Library UP-TO-DATE
:app:prepareComTwitterSdkAndroidTwitterCore150Library UP-TO-DATE
:app:prepareIoFabricSdkAndroidFabric136Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:fabricGenerateResourcesDebug
:app:processDebugResources
:app:generateDebugSources
:app:processDebugJavaRes UP-TO-DATE
:app:compileDebugJavaWithJavac
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:preDexDebug
:app:dexDebug
AGPBI: {"kind":"simple","text":"UNEXPECTED TOP-LEVEL EXCEPTION:","sources":[{}]}
AGPBI: {"kind":"simple","text":"com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.merge.DexMerger.merge(DexMerger.java:189)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.dexer.Main.run(Main.java:246)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.dexer.Main.main(Main.java:215)","sources":[{}]}
AGPBI: {"kind":"simple","text":"\tat com.android.dx.command.Main.main(Main.java:106)","sources":[{}]}
FAILED
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':app:dexDebug'.
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 13.002 secs
But when i remove compile 'io.socket:socket.io-client:0.6.1', sync and run the app.
Everything works fine. Please help.
Thanks in advance.
Hi The app connects to http://chat.socket.io but when I change it to the locally hosted address say http://192.168.1.2:3000 , it doesn't connect. Can you please help ?
Hi nkzawa,
May I know if this lib support namespace ?
Need to integration with nodejs server, Automattic/socket.io.
Thanks.
I tried to run this project on android studio 2.2.2
But it give me error
Failed to resolve:io.socket:socket.io-client:0.8.1
So I changed the dependencies like below
compile ('io.socket:socket.io-client:0.5.0') {
exclude group: 'org.json', module: 'json'
}
But same result.
Any advance ?
Can I send back Ack to server after I have received an event from the server?!
Thanks.
Hello,
can anyone tellme o give me a advice to send file from android app to nodejs server via http post, i mean upload any type of file (pdf, docx, xlsx, jgp, avi, etc.) via http.
In the android library, socket.id()
returns the id of the socket, however, there is no method (that I found in the jar file
) that lets us set the socket id.
How can I set the socket id for my communication. In the nodejs sample, setting socket.id = "customName"
works allowing us to decide our own name space for the sockets. Is there such an implementation in android?
I am developing a chat app wherein I want the socket.id()
of the users to be their username itself. So irrespective of when they connect, instead of getting a random id, it is fixed to their username. I plan to set the id as soon as a connection is made.
In Nodejs my code is following -
io.on('connection', (socket)=>{
console.log('new connection received');
console.log(socket.id)
socket.id = "username"
console.log(socket.id)
//other methods
}
This changes the socket id, but io.to(id).emit('new_message', data)
does not work. If i use the random id generated, then this method is working just fine.
Please advise.
Hello,
I can't setup port with IO.Options in Android, When socket.connect(), it always connect to port 80,
try to add port in host url > "http://host : port", but useless, and i use example both Node.js server
and Android, Node.js can get port 3000, Android's socket.connect() can't...
Could someone know this issue ? many thanks!!
I have imported this demo app. It works fine with http://chat.socket.io . But if I change the url to localhost http://192.168.0.23::3000 I am getting "io.socket.engineio.client.EngineIOException: xhr poll error" . I am using "srv-SocketChat" server code implementation to check the app.
Hi i tried add the .jar's, i tried add older libreries and only in one of my disp for bug this error out.
E/dalvikvm: Could not find class 'okhttp3.OkHttpClient$Builder', referenced from method io.socket.engineio.client.transports.WebSocket.doOpen
05-17 17:37:06.707 30194-31321/mx.com.avanceytec.ventascampo E/AndroidRuntime: FATAL EXCEPTION: EventThread
Process: mx.com.avanceytec.ventascampo, PID: 30194
java.lang.NoClassDefFoundError: okhttp3.OkHttpClient$Builder
this are my dependencies:
_dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile('org.apache.httpcomponents:httpclient-android:4.3.5.1') {
exclude module: 'com.squareup.okio'
}
compile('io.socket:socket.io-client:0.7.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:design:23.2.0'
compile 'com.android.support:support-v4:23.2.0'
compile 'com.loopj.android:android-async-http:1.4.7'
compile 'com.google.android.gms:play-services-location:8.4.0'
compile 'com.android.support:cardview-v7:23.2.0'
compile 'com.android.support:recyclerview-v7:23.2.0'
compile 'com.google.android.gms:play-services:8.4.0'
//compile 'com.github.gcacace:signature-pad:1.1.0'
}_
Help me please. Thanks
Hello. Is there a JAR file or an eclipse project that can be used?
For my NodeJS server code, I'm using the chat server code that is linked to in the socket io android tutorial.
I'm following the tutorial above to a tee in my android project.
build.gradle
:
...
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.github.nkzawa:socket.io-client:0.3.0'
}
AndroidManifest.xml
:
...
<uses-permission android:name="android.permission.INTERNET" />
...
MainActivity.java
:
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
public class MainActivity extends AppCompatActivity {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://chatserver:3000");
Log.e("CONNECTED", "SUCCESS");
} catch (URISyntaxException e) {
Log.e("ERROR", "ERROR CONNECTING");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSocket.connect();
mSocket.emit("message", "message");
}
}
When I compile this, no matter what I put as the URL for IO.socket(<url>)
, it always logs out that it connected. When I load the app, it's supposed to emit message
and send "message"
, but I never get it on the server. I never even get a "user connected" log in my server log, which I have setup to log out anytime a something connects to it.
Just to test to make sure my server code isn't faulty, I created a client project in NodeJS:
client.js
:
var io = require('socket.io-client'),
socket = io.connect('http://localhost:3000');
socket.on('connect', function(){
console.log("connected")
});
And it and the server both log out 'connected' when I run it. So something is wrong with the java code.... I can't figure it out.
I have found issue when I try to run this demo on Android 6. "Join" button make no effect. On my Samsung Note 2 (Android 4.4.2) chat works like a charm.
Here is log:
I am getting this excepition after sometime
Thread[2,tid=5533,WaitingInMainSignalCatcherLoop,Thread*=0xaf444400,peer=0x12c8b080,"Signal Catcher"]: reacting to signal 3
and am not able to connect again to server.
I am trying to connect to server from background service.
After connecting sometime later the connection get closed automatically and not reconnecting again.
How to handle this exception?
Is there any callback to handle this?
And am not able to view this stack traces.
Wrote stack traces to '/data/anr/traces.txt'
Thanks
Force closed
When my network is broken ,and then connect . My socket.io will reconnect automatic,but then I cant send message?
I've implemented a port of this Lib into my Android app, and I can't seem to move to the chat fragment when I input a nickname.. Not sure if it's because it's not declared as MAIN in my Androidmanifest.xml file or what... But can someone please point me to the right direction... Thanks...
Hi, I would show external messages from the outside on the left side of the screen and messages sent by the myself on the right side of the screen. I've created two different item_message for the right side and for the left side, but I don't know how to implement this. Could you help me with a code snippet?
Thank you in advance.
I'm getting (Socket.EVENT_CONNECT_TIMEOUT after a minute and a half after my Internet connection was closed. How to reduce timeout?
True
when i compile using jar library and not using granle ..its force close ..so sad :'(
Sorry it's for another project
I am unable to find any reference to making connection to https server.
I have tested my server with a web based client and its working.
Such as 192.168.0.1:8888
Sir I have an issue listen socket from server . You make for group chat but I want one-one lisntening from server or you can say private chat only one person chat to other person please tell me how do I manage this
and is there proper documentation for this client functions?
thank you!
I am getting the above error error while running the code on emulator.
I have simply run the code on android studio.
Is there anything i need to change in the code before running?
Hi,
I read this interesting article about token based authorisation : https://auth0.com/blog/2014/01/15/auth-with-socket-io/
Does this library have the ability to send a query on connection?
Like show in this part of the code:
var socket = io.connect('', {
query: 'token=' + token
});
node disconnect after app closed so how is it possible to node connect always no matter , app is in background or closed?
in mSocket = IO.socket(Constants.CHAT_SERVER_URL)
i want to send basic authorization details "Authorization","Basic 1234567890"
please explain me how to send?
I'm implementing simple chat server that work fine in kind of browsers, but couldn't send message to specific user from android to other android device or android device to users which connected from browser, server said me user isn't connected, but in browser can detected correctly and sending message,i don't know whats problem, all of other feature work fine
Html for test and sending message to specific user:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
Document
</title>
</meta>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#login').click(function () {
socket.emit('login', {username: 'a', password: 'a'});
});
$('#mesage').click(function () {
socket.emit('requestMoney', 'mahdi');
});
});
</script>
<script>
var socket = new io.connect('http://192.168.1.35:3000', {
port : 3000,
transports: ['websocket']
});
socket.on('connect', function () {
console.log('connected!');
});
socket.on('message', function (message) {
console.log("hello ::::::::" + message);
});
socket.on('success', function (data) {
console.log(data);
});
</script>
</head>
<body>
<h3 id="login">login</h3>
<h3 id="mesage">mesage</h3>
</body>
</html>
My simplified nodejs server:
var socket = require('socket.io'),
express = require('express'),
app = express(),
server = require('http').createServer(app),
io = socket.listen(server),
port = process.env.PORT || 3000,
mysql = require('mysql'),
multer = require('multer'),
uuid = require('node-uuid'),
datetime = require('node-datetime'),
moment = require('moment'),
bcrypt = require('bcrypt'),
async = require('async'),
request = require('request'),
redis = require("redis"),
redisClient = redis.createClient(),
log = require('log4node');
var io_redis = require('socket.io-redis');
io.adapter(io_redis({host: 'localhost', port: 6379}));
require('sticky-socket-cluster/replace-console')();
require('sticky-socket-cluster')(options, start);
function start(port) {
io.sockets.on('connection', function (socket) {
socket.on('login', function (data) {
console.log(data.username);
login(data.username, data.password, function (success, value) {
if (success) {
redisClient.exists(data.username, function (err, doesExist) {
if (err) return;
if (!doesExist) {
log.info("saved to redis");
redisClient.set(data.username, socket.id, function (err, res) {
redisClient.set(data.username, socket.id);
});
}
else {
log.info("deleted and saved to redis");
redisClient.del(data.username);
redisClient.set(data.username, socket.id, function (err, res) {
redisClient.set(data.username, socket.id);
});
}
});
socket.emit('login', {result: true, id: value});
} else {
log.info("FAIL login");
socket.emit('login', {result: false});
}
});
});
socket.on('requestMoney', function (data) {
redisClient.get('mahdi', function (err, socketId) {
if (io.sockets.connected[socketId]) {
log.info('mahdi' + ' sent');
io.sockets.connected[socketId].emit('message', {username: 'Hey to :), inja ro bebin ;)'});
} else {
log.info('mahdi' + ' NOT LOGin');
}
});
});
});
server.listen(port, function () {
console.log('Express and socket.io listening on port ' + port);
});
}
...
Android Socket settings and options:
public class Application extends android.app.Application {
public static final boolean DEBUG = true;
public static Application application;
private static Context context;
public static String packageName;
public static Resources resources;
public static Socket CHAT_SOCKET;
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
}
@Override
public void onCreate() {
super.onCreate();
//@formatter:off
resources = this.getResources();
context = getApplicationContext();
packageName = getPackageName();
//@formatter:on
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = true;
try {
CHAT_SOCKET = IO.socket(ClientSettings.getChatAddress(), opts);
} catch (URISyntaxException e) {
e.printStackTrace();
Log.e("SOCKET.IO ", e.getMessage());
}
}
public static Context getContext() {
return context;
}
public Socket getSocket() {
return CHAT_SOCKET;
}
}
Hi,
I downloaded you source code and changed the CHAT_SERVER_URL to my localhost nodejs socket io instance and its always throwing error Connect_error. I tried with connecting to my localhost server using the plain html for testing purpose and it worked without any issues. Could you please check where I'm doing wrong?
server code: v.1.3.6
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;
var io = require('socket.io')(server);
io.on('connection', function (socket) {
var addedUser = false;
console.log("connected");
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
console.log(data);
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
// remove the username from global usernames list
if (addedUser) {
delete usernames[socket.username];
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});
My test index.html file -
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script type="text/javascript">
var socket = io.connect('http://localhost:9000');
//socket.connect();
socket.on('connect', function() {
console.log('connected');
});
socket.emit("new message", "Test message from client");
</script>
Can this be used on Primus?
try {
IO.Options options = new IO.Options();
options.query = "cookie=" + session + "&propname=sathish";
mSocket = IO.socket(AppController.URL, options);
app.setSocket(mSocket);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
i am getting the error at connection stating that
io.socket.engineio.client.EngineIOException: server error
below is complete code
import android.os.Bundle;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends AppCompatActivity {
private Socket mSocket;
private List<Message> mMessages = new ArrayList<Message>();
TextView response;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
response = (TextView) findViewById(R.id.response);
AppController app = (AppController) getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("connect", onConncet);
mSocket.on("message", onNewMessage);
mSocket.connect();
}
private Emitter.Listener onConnectError = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String str = args[0].toString();
Log.d("see--->>", str);
Toast.makeText(MainActivity.this, "Error Connection" + str, Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
Log.d("response from servaer", data.toString());
addLog(data.toString());
Toast.makeText(MainActivity.this, "Message" + data.toString(), Toast.LENGTH_LONG).show();
data.getString("");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
};
private Emitter.Listener onConncet = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("Connect To servaer", "Connection Suicessfull");
Toast.makeText(MainActivity.this, "Connection Successfull", Toast.LENGTH_LONG).show();
}
});
}
};
private void addLog(String message) {
response.setText(message);
}
@Override
protected void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("new message", onNewMessage);
}
}
Hi all. in my application i cant create simple single service to connect to Socket, in my application after first run application i can emmit one request, but after close application and run again, my app send twice request to socket.io, and after clear app from recent application, that send multiple request to socket.io. please help me to create single service to create one connection, Thanks
My Service:
public class SignalChatServiceProvider extends Service {
public static SignalChatServiceProvider instance = null;
public static boolean isInstanceCreated() {
return instance == null ? false : true;
}
@Override
public IBinder onBind(Intent intent) {
return myBinder;
}
private final IBinder myBinder = new LocalBinder();
public class LocalBinder extends Binder {
public SignalChatServiceProvider getService() {
return SignalChatServiceProvider.this;
}
}
@Override
public void onCreate() {
super.onCreate();
realm = Realm.getDefaultInstance();
signalApplication = (SignalApplication) getApplication();
EventBus.getDefault().register(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
connectConnection();
Log.e("EJRA...", "");
return START_STICKY;
}
private Runnable onTypingTimeout = new Runnable() {
@Override
public void run() {
}
};
private void connectConnection() {
instance = this;
signalApplication.CHAT_SOCKET = signalApplication.getSocket();
signalApplication.getSocket().on(Socket.EVENT_CONNECT_ERROR, onConnectError);
signalApplication.getSocket().on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
signalApplication.getSocket().on(Socket.EVENT_CONNECT, onConnect);
signalApplication.getSocket().on("new message", onNewMessage);
signalApplication.getSocket().on("user joined", onUserJoined);
signalApplication.getSocket().on("getProductImages", getProductImages);
signalApplication.getSocket().connect();
}
private void disconnectConnection() {
instance = null;
signalApplication.getSocket().disconnect();
signalApplication.getSocket().off(Socket.EVENT_CONNECT, onConnect);
signalApplication.getSocket().off(Socket.EVENT_DISCONNECT, onDisconnect);
signalApplication.getSocket().off(Socket.EVENT_CONNECT_ERROR, onConnectError);
signalApplication.getSocket().off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
signalApplication.getSocket().off("new message", onNewMessage);
signalApplication.getSocket().off("user joined", onUserJoined);
signalApplication.getSocket().off("getProductImages", getProductImages);
signalApplication.getSocket().disconnect();
}
@Override
public void onDestroy() {
super.onDestroy();
disconnectConnection();
if (!realm.isClosed())
realm.close();
}
}
ActivityMain:
if (signalApplication.getSocket() != null && !SignalChatServiceProvider.isInstanceCreated()) {
startService(new Intent(getBaseContext(), SignalChatServiceProvider.class));
}
Application class:
public class SignalApplication extends Application {
public static List<MarketsBaseInformation> market_list_cache_data;
public static Socket CHAT_SOCKET;
@Override
public void onCreate() {
super.onCreate();
resources = this.getResources();
context = getApplicationContext();
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = true;
try {
CHAT_SOCKET = IO.socket(ClientSettings.getChatAddress(), opts);
} catch (URISyntaxException e) {
e.printStackTrace();
Log.e("SOCKET.IO ", e.getMessage());
}
}
public Socket getSocket() {
return CHAT_SOCKET;
}
}
I don't know how to Push Notification Heartbeat Network Package from client to service . Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.