i am trying to build my chat app. The server side and client side code is attached. when i install it it successfully get installed without giving any error. but it could not communicate to the server i also want that server can handle multiple clients. One thing that is surprising when i install it in my phone it successfully get installed and communicate to server but on any other device or emulator it could not communicate?. how can make this app that multiple clients connects on server and chat?
server side script
const express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.get('/', (req, res) => {
res.send('Chat Server is running on port 5000')
});
app.set('port',(process.env.PORT||3000))
io.on('connection', (socket) => {
console.log('user connected. id: '+socket.id)
socket.on('join', function(userNickname) {
console.log(userNickname +" : has joined the chat " );
socket.broadcast.emit('userjoinedthechat ',userNickname +" has joined the chat ");
});
socket.on('messagedetection', (senderNickname,messageContent) => {
//log the message in console
console.log(senderNickname+" :" +messageContent)
//create a message object
let message = {"message":messageContent, "senderNickname":senderNickname}
// send the message to the client side
io.emit('message', message );
});
socket.on('disconnect', function() {
console.log( ' user has left ')
socket.broadcast.emit("userdisconnect"," user has left ")
});
});
server.listen(app.get('port'),function(){
console.log('Node app is running on port ',app.get('port'));
});
**Client side**
try {
socket = IO.socket("http://ipaddress:8080").connect();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!messagetxt.getText().toString().isEmpty()){
socket.emit("messagedetection", Nickname, messagetxt.getText().toString());
messagetxt.setText(" ");
}
}
});
socket.on("join", new Emitter.Listener() {
public void call(final Object... args) {
runOnUiThread(new Runnable() {
public void run() {
String data = (String) args[0];
socket.emit("join"+Nickname);
}
});
}
});
socket.on("disconnect", new Emitter.Listener() {
public void call(final Object... args) {
runOnUiThread(new Runnable() {
public void run() {
String data = (String) args[0];
socket.emit("disconnect",Nickname);
// Toast.makeText(ChatBoxActivity.this,data,Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("message", new Emitter.Listener() {
Message m;
public void call(final Object... args) {
runOnUiThread(new Runnable() {
public void run() {
JSONObject data = (JSONObject) args[0];
try {
//extract data from fired event
String nickname = data.getString("senderNickname");
String message = data.getString("message");
m = new Message(nickname,message);
MessageList.add(m);
chatBoxAdapter = new ChatBoxAdapter(MessageList,ChatBoxActivity.this);
chatBoxAdapter.notifyDataSetChanged();
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
enter code here
I tried with node and html. it's working
Client Side
console.log('Server connection started');
var socket = io();
var date = new Date();
var Nickname = "Karthik"+ date.getTime();
socket.on('join', (data) => {
console.log('join', data);
socket.emit("join", Nickname);
})
socket.on('disconnect', (data) => {
console.log('disconnect', data);
socket.emit("disconnect", Nickname);
})
socket.on('message', (data) => {
console.log('message', data);
// socket.emit("message", Nickname);
})
socket.emit("messagedetection", Nickname, 'Hi Test.');
console.log('Server connected', socket);
please check the emit and on function.
Server side
const express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static('node_modules'))
app.use(express.static('public'))
app.get('/', (req, res) => {
res.send('Chat Server is running on port 5000')
});
app.set('port', (process.env.PORT || 3000))
io.on('connection', (socket) => {
console.log('user connected. id: ' + socket.id)
socket.on('join', function (userNickname) {
console.log(userNickname + " : has joined the chat ");
socket.broadcast.emit('userjoinedthechat ', userNickname + " has joined the chat ");
});
socket.on('messagedetection', (senderNickname, messageContent) => {
console.log(senderNickname + " :" + messageContent)
//create a message object
let message = { "message": messageContent, "senderNickname": senderNickname }
// send the message to the client side
io.emit('message', message);
});
socket.on('disconnect', function () {
console.log(' user has left ')
socket.broadcast.emit("userdisconnect", " user has left ")
});
});
server.listen(app.get('port'), function () {
console.log('Node app is running on port ', app.get('port'));
});
Related
i am trying to make an android realtime chat using node js server and socket.io this is the chatbox activity :
public class ChatBoxActivity extends AppCompatActivity {
public RecyclerView myRecylerView ;
public List<Message> MessageList ;
public ChatBoxAdapter chatBoxAdapter;
public EditText messagetxt ;
public Button send ;
//declare socket object
private Socket socket;
public String Nickname ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_box);
messagetxt = (EditText) findViewById(R.id.message) ;
send = (Button)findViewById(R.id.send);
// get the nickame of the user
Nickname= (String)getIntent().getExtras().getString(MainActivity.NICKNAME);
//connect you socket client to the server
try {
socket = IO.socket("http://10.0.2.2:3000");
socket.connect();
socket.emit("join", Nickname);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//setting up recyler
MessageList = new ArrayList<>();
myRecylerView = (RecyclerView) findViewById(R.id.messagelist);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
myRecylerView.setLayoutManager(mLayoutManager);
myRecylerView.setItemAnimator(new DefaultItemAnimator());
// message send action
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//retrieve the nickname and the message content and fire the event messagedetection
if(!messagetxt.getText().toString().isEmpty()){
socket.emit("messagedetection",Nickname,"jfjdjfj");
messagetxt.setText(" ");
}
}
});
//implementing socket listeners
socket.on("userjoinedthechat", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("userdisconnect", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("message", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
//extract data from fired event
String nickname = data.getString("senderNickname");
String message = data.getString("message");
// make instance of message
Message m = new Message(nickname,message);
//add the message to the messageList
MessageList.add(m);
// add the new updated list to the dapter
chatBoxAdapter = new ChatBoxAdapter(MessageList);
// notify the adapter to update the recycler view
chatBoxAdapter.notifyDataSetChanged();
//set the adapter for the recycler view
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
}
this is node js server code :
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
io.on('connection',function(socket){
console.log('one user connected '+socket.id);
socket.on('CHAT' , function (data) {
console.log('======CHAT message========== ');
console.log(data);
socket.emit('CHAT',data);
});
socket.on('disconnect',function(){
console.log('one user disconnected '+socket.id);
});
})
http.listen(3000,function(){
console.log('server listening on port 3000');
})
details about the error :
the server is running correctly it's printing 'server listening on port 3000' in the console . also when i join the chat the socket 'join' and 'disconnect' are emmitted since i get this in my console log:
one user connected xVs1-xYtvNA5sd-dAAAA
one user disconnected xVs1-xYtvNA5sd-dAAAA
only the connect and disconnect socket events are emitted but the send and recevie messages aren't being emitted .
You just need to give the recyclerView an adapter at the same time you give it the layoutManager... It is skipping the layout here when getting the adaper
[UPDATE]
For the socket not emmiting the message on your server you are not listening for the "message" or on the android side you are not listening for the "chat" I would modify your server side code to match your android application as such
Final code:
public class ChatBoxActivity extends AppCompatActivity {
public RecyclerView myRecylerView ;
public List<Message> MessageList ;
public ChatBoxAdapter chatBoxAdapter;
public EditText messagetxt ;
public Button send ;
//declare socket object
private Socket socket;
public String Nickname ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_box);
messagetxt = (EditText) findViewById(R.id.message) ;
send = (Button)findViewById(R.id.send);
// get the nickame of the user
Nickname= (String)getIntent().getExtras().getString(MainActivity.NICKNAME);
//connect you socket client to the server
try {
socket = IO.socket("http://10.0.2.2:3000");
socket.connect();
socket.emit("join", Nickname);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//setting up recyler
MessageList = new ArrayList<>();
myRecylerView = (RecyclerView) findViewById(R.id.messagelist);
// message send action
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//retrieve the nickname and the message content and fire the event messagedetection
if(!messagetxt.getText().toString().isEmpty()){
socket.emit("message",Nickname,"jfjdjfj");
messagetxt.setText(" ");
}
}
});
//implementing socket listeners
socket.on("userjoinedthechat", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("userdisconnect", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String) args[0];
Toast.makeText(ChatBoxActivity.this,data, Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on("message", new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
//extract data from fired event
String nickname = data.getString("senderNickname");
String message = data.getString("message");
// make instance of message
Message m = new Message(nickname,message);
//add the message to the messageList
MessageList.add(m);
// add the new updated list to the dapter
chatBoxAdapter = new ChatBoxAdapter(MessageList);
// notify the adapter to update the recycler view
chatBoxAdapter.notifyDataSetChanged();
//set the adapter for the recycler view
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
myRecylerView.setLayoutManager(mLayoutManager);
myRecylerView.setItemAnimator(new DefaultItemAnimator());
myRecylerView.setAdapter(chatBoxAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
}
Server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.send('<h1>Hello world</h1>');
});
io.on('connection',function(socket){
console.log('one user connected '+socket.id);
socket.on('message' , function (data) {
console.log('======CHAT message========== ');
console.log(data);
socket.emit('message',data);
});
socket.on('disconnect',function(){
console.log('one user disconnected '+socket.id);
});
})
http.listen(3000,function(){
console.log('server listening on port 3000');
})
I want to create a connection between my node.js page and my java application
I'm trying to link this node.js page, this page :
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
console.log("Load ...");
res.sendFile(__dirname+"/index.html");
});
io.on('connection', function(socket){
console.log('one user connected : ' + socket.id);
});
http.listen(3000 ,function(){
console.log('Start server on port 3000');
});
with this java code:
My socke, this page is just to tell me if someone has joined the socket, the page is hosted on http://192.168.0.12:3000/ :
private Socket socket;
{
try{
socket = IO.socket("http://192.168.0.12:3000");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
My listeners, here I'am just testing what type of errors i get:
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Connect", Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Errors", Toast.LENGTH_SHORT).show();
}
});
}
});
socket.on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
#Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Timeout", Toast.LENGTH_SHORT).show();
}
});
}
});
socket.connect();
I always have the same error Socket.EVENT_CONNECT_ERROR.
My node.js work on network but
My code node.js works for internet browsers but not on android, I think this from configuration but what I do not know.
Thank you
First,check if your android device can even access the node.js server
go the browser in your device and request the same url
it's maybe you cannot access the resource in the first place
The solution:
just add this in manifest:
android:usesCleartextTraffic="true"
I can not connect with AWS iot when I'm going to create new key and certificate.
It gives me error as under:
com.amazonaws.AmazonServiceException: User:
arn:aws:sts::964546574005:assumed-role/Cognito_GTekPool3Unauth_Role/CognitoIdentityCredentials
is not authorized to perform:
iot:CreateKeysAndCertificate on resource: * (Service: AWSIot; Status
Code: 403; Error Code: AccessDeniedException; Request ID:
b1c4acdd-b1ba-11e8-9d83-772e33c0d6b2)
Below is what I have done in code:
if (clientKeyStore == null) {
Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate.");
new Thread(new Runnable() {
#Override
public void run() {
try {
// Create a new private key and certificate. This call
// creates both on the server and returns them to the
// device.
CreateKeysAndCertificateRequest createKeysAndCertificateRequest =
new CreateKeysAndCertificateRequest();
createKeysAndCertificateRequest.setSetAsActive(true);
final CreateKeysAndCertificateResult createKeysAndCertificateResult;
createKeysAndCertificateResult =
mIotAndroidClient.createKeysAndCertificate(createKeysAndCertificateRequest);
Log.i(LOG_TAG,
"Cert ID: " +
createKeysAndCertificateResult.getCertificateId() +
" created.");
// store in keystore for use in MQTT client
// saved as alias "default" so a new certificate isn't
// generated each run of this application
AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId,
createKeysAndCertificateResult.getCertificatePem(),
createKeysAndCertificateResult.getKeyPair().getPrivateKey(),
keystorePath, keystoreName, keystorePassword);
// load keystore from file into memory to pass on
// connection
clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
keystorePath, keystoreName, keystorePassword);
// Attach a policy to the newly created certificate.
// This flow assumes the policy was already created in
// AWS IoT and we are now just attaching it to the
// certificate.
AttachPrincipalPolicyRequest policyAttachRequest =
new AttachPrincipalPolicyRequest();
policyAttachRequest.setPolicyName(AWS_IOT_POLICY_NAME);
policyAttachRequest.setPrincipal(createKeysAndCertificateResult
.getCertificateArn());
mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest);
runOnUiThread(new Runnable() {
#Override
public void run() {
btnConnect.setEnabled(true);
}
});
} catch (Exception e) {
Log.e(LOG_TAG,
"Exception occurred when generating new private key and certificate.",
e);
}
}
}).start();
}
}
View.OnClickListener connectClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "clientId = " + clientId);
try {
mqttManager.connect(clientKeyStore, new AWSIotMqttClientStatusCallback() {
#Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
Log.d(LOG_TAG, "Status = " + String.valueOf(status));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (status == AWSIotMqttClientStatus.Connecting) {
tvStatus.setText("Connecting...");
} else if (status == AWSIotMqttClientStatus.Connected) {
tvStatus.setText("Connected");
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
tvStatus.setText("Reconnecting");
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
tvStatus.setText("Disconnected");
} else {
tvStatus.setText("Disconnected");
}
}
});
}
});
} catch (final Exception e) {
Log.e(LOG_TAG, "Connection error.", e);
tvStatus.setText("Error! " + e.getMessage());
}
}
};
Certificate from keystore is not reading and giving me IOexception.
The error you are getting:
com.amazonaws.AmazonServiceException: User: arn:aws:sts::964546574005:assumed-role/Cognito_GTekPool3Unauth_Role/CognitoIdentityCredentials is not authorized to perform:
indicates that you have missing permission for the specified role. You will have to attach a valid policy which allows you to call the createKeysAndCertificate API on the service.
Thanks,
Rohan
I am trying to develop a chat application but instead of Google message service I tried writing xmmp node server.
I am able to login in to server.But getting message saying feature not implemented.
<iq to='359648069251166#10.10.25.126/Smack' id='cu03M-5' type='error'><error type='cancel'><feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></iq>
android code
final TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setServiceName(IPADRESS)
.setHost(IPADRESS)
.setPort(5222)
.build();
AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
conn2.setPacketReplyTimeout(1000);
SmackConfiguration.DEBUG = true;
conn2.connect();
conn2.addConnectionListener(new ConnectionListener() {
#Override
public void connected(XMPPConnection connection) {
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
}
#Override
public void connectionClosed() {
}
#Override
public void connectionClosedOnError(Exception e) {
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int seconds) {
}
#Override
public void reconnectionFailed(Exception e) {
}
});
conn2.addAsyncPacketListener(new PacketListener() {
#Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
if (packet != null) {
Log.d("stanza", "received" + packet.toXML());
Toast.makeText(getApplicationContext(), packet.toXML(), Toast.LENGTH_LONG).show();
}
}
}, new PacketFilter() {
#Override
public boolean accept(Stanza packet) {
return true;
}
});
Roster roster = Roster.getInstanceFor(conn2);
//Get all rosters
Collection<RosterEntry> entries = roster.getEntries();
//loop through
for (RosterEntry entry : entries) {
//example: get presence, type, mode, status
Presence entryPresence = roster.getPresence(entry.getUser());
Presence.Type userType = entryPresence.getType();
Presence.Mode mode = entryPresence.getMode();
String status = entryPresence.getStatus();
Log.d("stanza",userType+" "+status);
}
roster.addRosterListener(new RosterListener() {
#Override
public void presenceChanged(Presence presence) {
//Called when the presence of a roster entry is changed
}
#Override
public void entriesUpdated(Collection<String> arg0) {
// Called when a roster entries are updated.
}
#Override
public void entriesDeleted(Collection<String> arg0) {
// Called when a roster entries are removed.
}
#Override
public void entriesAdded(Collection<String> arg0) {
// Called when a roster entries are added.
}
});
conn2.login(mngr.getDeviceId(), "secret");
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("I’m available");
conn2.sendPacket(presence);
ChatManager chatManager = ChatManager.getInstanceFor(conn2);
Chat chat = chatManager.createChat(mngr.getDeviceId(), new ChatMessageListener() {
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
Log.d("stanza", message.toString());
// processMessage(chatMessage);
}
}
});
// Add a packet listener to get messages sent to us
Message message = new Message();
message.setFrom(mngr.getDeviceId());
message.setTo(mngr.getDeviceId());
message.setType(Message.Type.chat);
message.setSubject("jhelloworld");
chat.sendMessage(message);
}catch (Exception e){
Log.d("error",e.getMessage());
}
I took server from here.
server side code.
var startServer = function (done) {
// Sets up the server.
server = new xmpp.C2S.TCPServer({
port: 5222,
domain: 'localhost'
})
server.on('connection', function (client) {
// That's the way you add mods to a given server.
// Allows the developer to register the jid against anything they want
client.on('register', function (opts, cb) {
console.log('REGISTER')
cb(true)
})
// Allows the developer to authenticate users against anything they want.
client.on('authenticate', function (opts, cb) {
console.log('server:', opts.username, opts.password, 'AUTHENTICATING')
if (opts.password === 'secret') {
console.log('server:', opts.username, 'AUTH OK')
cb(null, opts)
} else {
console.log('server:', opts.username, 'AUTH FAIL')
cb(false)
}
})
client.on('online', function () {
console.log('server:', client.jid.local, 'ONLINE')
client.send("")
})
// Stanza handling
client.on('stanza', function (stanza) {
console.log('server:', client.jid.local, 'stanza', stanza.toString())
var from = stanza.attrs.from
stanza.attrs.from = stanza.attrs.to
stanza.attrs.to = from
client.send(stanza)
})
// Stanza handling
client.on('chat', function (stanza) {
console.log('server:', client.jid.local, 'chat', stanza.toString())
client.send(stanza)
});
// On Disconnect event. When a client disconnects
client.on('disconnect', function () {
console.log('server:', client.jid.local, 'DISCONNECT')
})
})
server.on('listening', done)
}
startServer(function (){
console.log("server localhost started at 5222 localport");
});
I tried many solution from stackoverflow and smack community but didnt.
help will be appreciated.
I wrote this node.js server.But when I send data from android with socket.io module.But I get errors.Please help me? how can ı send data(sender,message) from android to node.js server.
node.js server
var io = require('socket.io').listen(8001);
var connectCounter=0;
console.log('Server running :');
// open the socket connection
io.sockets.on('connection', function (socket) {
connectCounter++;
console.log('bağlantı başarılı sayı:');
console.log(connectCounter);
//Recode user online
var sender;
socket.on('user-online',function(data){
console.log('user-online');
var obj = JSON.parse(data);
sender = obj.sender;
console.log(sender);
socket.broadcast.emit('online',{sender : sender});
});
socket.on('message', function(message){
console.log('on-message');
var obj = JSON.parse(message);
socket.broadcast.emit('event',{sender : obj.sender, message : obj.message});
console.log(message);
});
socket.on('disconnect', function (socket){
console.log('disconnect');
connectCounter--;
socket.broadcast.emit('offline',{sender : sender})
});
});
It's a android codes.
btnOK.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
strUserName = edtUserName.getText().toString();
if (strUserName != null && strUserName.length() > 0 || !"".equals(strUserName)) {
Intent intent = new Intent(getApplicationContext(), ScreenChat.class);
intent.putExtra("UserName", strUserName);
startActivity(intent);
edtUserName.getText().clear();
}else {
Toast.makeText(getApplicationContext(), "user name null", Toast.LENGTH_SHORT).show();
return;
}
SocketIO socket;
try {
socket = new SocketIO("http://192.168.9.43:8001/");
socket.connect(new IOCallback() {
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
public void onDisconnect() {
System.out.println("Connection terminated.");
}
public void onConnect() {
System.out.println("Connection established");
}
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
}
});
// This line is cached until the connection is establisched.
socket.send("Hello Server!");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#SuppressWarnings("unused")
public void onClick(final DialogInterface arg0, final int arg1) {
// TODO Auto-generated method stub
}
});
When I click btnOK(you can see above code), I get this error:
You are sending a string, and trying to parse it as JSON.
socket.send("Hello Server!");
var obj = JSON.parse(message);
"Hello Server!" is not valid JSON.