I'm making an app with socket IO, it connects correctly to the server, but it doesn't listen to events.
Here's part of my code:
private Socket mSocket;
{
try {
mSocket = IO.socket(ip+":8000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ads);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.connect();
mSocket.on("send file", onSendFile);
}
private Emitter.Listener onSendFile = new Emitter.Listener() {
#Override
public void call(Object... args) {
String data = (String) args[0];
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
mSocket.emit("fileok", "OKIDOKI");
}
};
try to show toast on UI thread instead of different thread using getActivity().runOnUiThread
private Emitter.Listener onSendFile = new Emitter.Listener() {
#Override
public void call(Object... args) {
String data = (String) args[0];
mSocket.emit("fileok", "OKIDOKI");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
}
});
}
};
Related
I am trying to connect Node server Socket From android for Live Order track purpose, I couldn't connect to the server in Version 9 Android devices but works fine in lower versions. I didn't get LatLog From Server, but it is fetching in lower Devices.
I am using FCM as well for Notification purposes.
android:usesCleartextTraffic="true"
The above Manifest line not worked in my case
Kindly find my code below
private void ConnectSocket() {
try {
final JSONObject objInit = new JSONObject();
// objInit.put ("user_joined", bookingKey);
objInit.put("user_joined", bookingKey);
if (socket == null) {
socket = IO.socket(Urls.socketUrl);
} else {
System.out.println("Socket is already connected");
}
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
socket.emit("user_joined", bookingKey);
locationList.clear();
}
}).on("authenticated", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("event", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("newlocation", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
})
.on(bookingKey, new Emitter.Listener() {
#Override
public void call(Object... args) {
final String taxiDetails = args[0].toString();
System.out.println("Received from Socket :" + args[0].toString());
try {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject Job_CarDetails = new JSONObject(taxiDetails);
String latitude = Job_CarDetails.getString("latitude");
String longitude = Job_CarDetails.getString("longitude");
if (locationList.size() == 0) {
MarkerOptions mMarkerOptions = new MarkerOptions().position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_van));
Marker mMarker = googleMap.addMarker(mMarkerOptions);
MarkerList markerList = new MarkerList();
markerList.setLatitude(latitude);
markerList.setLongitude(longitude);
markerList.setMarker(mMarker);
locationList.add(markerList);
} else {
LatLng mToPosition = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
if (!socket.connected()) {
try {
socket.connect();
socket.emit("user_joined", bookingKey);
locationList.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
}
}
How can I modify my code, to connect version 9 Devices to the server?? Any help would be appreciated.
This issue was not from the Android side, it is on the server-side. This case raised because of local Server pointing when the Server moved to live Server, Socket Connection Worked.
Thanks.
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'm trying to use socket.io/engine.io (https://github.com/socketio/socket.io-client-java) to connect to websocket server. I wrote any point as the guthub page described, but I have no connection, even no log that something happens or not.. EVENT_CONNECTED is not fired. I don't know what is the problem- maybe socket.IO is not working with android 5.1UP? The websocket server is tested with JS and is working fine.
There is my very simple code, it will be great if you know socket.io and could take a look:
Ws implementation:
public class MyWsImplInIo {
private Socket socket;
public void start(){
try{
socket = IO.socket("http://192.168.1.8:8080/tmed-webserver/call");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
socket.emit("foo", "hi");
socket.disconnect();
}
}).on("event", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
}
});
socket.connect();
} catch(Exception e){
Log.d("WEBSOCKET", "SOME ERROR");
e.printStackTrace();
}
}
}
And a main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyWsImplInIo a = new MyWsImplInIo();
a.start();
}
}
I am working on an android chat application .I am not able to connect to my server using Socket.Io client in android.
1.ChatActivity.java
public class ChatActivity extends Activity {
EditText edMessage;
private Socket mSocket;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("Socket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
edMessage = (EditText) findViewById(R.id.edtMessage);
String message = edMessage.getText().toString().trim();
mSocket.connect();
// mSocket.emit("subscribe", "Testing");
mSocket.on("subscribe", subscribe);
}
private Emitter.Listener subscribe = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
String room = (String) args[0];
Log.e("Response", room);
}
});
}
};
}
Please help me to solve the issue.I am not able to verify whether the server is connected or not .
I use sails v0.11.2 and try to connect to web sockets with https://github.com/socketio/socket.io-client-java
My problem is when I logout from my server (I use passport.js) the disconnect event was fired correctly but I can't reconnect after this event append.
Here is my code :
socket = IO.socket(Constants.LOCAL_URL + "?__sails_io_sdk_version=0.11.0");
socket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
Transport transport = (Transport) args[0];
transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
#SuppressWarnings("unchecked")
Map<String, List<String>> headers = (Map<String, List<String>>) args[0];
// modify request headers
headers.put("Cookie", Arrays.asList(COOKIE));
}
});
}
});
socket.on(Socket.EVENT_ERROR, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onError();
}
Log.e("test", "ERROR");
}
}).on(Socket.EVENT_CONNECT, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
listener.onConnect();
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
listener.onDisconnect();
}
}).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onConnectError();
}
}
}).on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onConnectError();
}
}
}).on(Socket.EVENT_RECONNECT_ERROR, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onConnectError();
}
}
}).on(Socket.EVENT_RECONNECT_FAILED, new Emitter.Listener()
{
#Override
public void call(Object... args)
{
if (listener != null)
{
listener.onConnectError();
}
}
});
socket.connect();
And here is my listener when I try to reconnect after is disconnect event :
SocketIOManager.SocketConnexionListener socketConnexionListener = new SocketIOManager.SocketConnexionListener()
{
#Override
public void onConnect()
{
Log.e("test", "CONNECT");
}
#Override
public void onError()
{
Log.e("test", "ERROR");
}
#Override
public void onDisconnect()
{
createSocket();//Call the code above to create a new socket or call socket.connect(); but it's not working and no error throw...
Log.e("test", "DISCON");
}
#Override
public void onConnectError()
{
Log.e("test", "CONNECT ERROR");
}
};