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 .
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'm new to android and I tried to create a chat app using Smack 4.1 and Ejabberd.
I have implemented a group chat using MultiUserChat. I have added Messagelistener to listen every new incoming message and add into adapter.
When I enter into chat room and start chat list works very well.
But the problem is when I back to the any other intent and then go back into chat room then when someone messages me, it is received multiple times.
Maybe I set messagelistner multiple times.
Here is my code Activity Class -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatiing);
user2 = getIntent().getExtras().getString("JID");
msg_edittext = (EditText)findViewById(R.id.messageEditText);
msgListView = (ListView)findViewById(R.id.msgListView);
msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatlist = new ArrayList<ChatMessage>();
chatlist.clear();
chatAdapter = new ChatAdapter(ChattingGroup.this,chatlist);
msgListView.setAdapter(chatAdapter);
autoJoinRoom(user1,room_name,new View(getApplicationContext()));
ImageButton sendButton = (ImageButton)findViewById(R.id.sendMessageButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendTextMessage(view);
}
});
}
public void autoJoinRoom(String user, String room, View view){
LoginActivity activity = new LoginActivity();
XMPPTCPConnection connection = activity.getmService().xmpp.connection;
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
MultiUserChat multiUserChat = manager.getMultiUserChat(room);
try {
multiUserChat.join(user,"12345");
chatlist.clear();
multiUserChat.addMessageListener(new MessageListener() {
#Override
public void processMessage(Message message) {
if(message.getBody() != null){
Log.d("New Message Received",message.getBody());
chatlist.add(message.getBody());
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/* Change adapter */
((BaseAdapter) msgListView.getAdapter()).notifyDataSetChanged();
}
});
}
}
});
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
}
}
How can I solve this problem ?
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();
}
});
}
};
I am trying to learn basic MQTT integration in Android. I am using a mosquitto broker to publish and subscribe messages. I am running the code on a real device and getting this exception :
Unable to connect to server (32103) - java.net.ConnectException:
failed to connect to /192.168.0.103 (port 1883) after
30000ms: isConnected failed: ECONNREFUSED
Here's my code:
public class HomeActivity extends AppCompatActivity{
private MqttAndroidClient client;
private final MemoryPersistence persistence = new MemoryPersistence();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.0.103:1883", "androidSampleClient", persistence);
mqttAndroidClient.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
System.out.println("Connection was lost!");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message Arrived!: " + topic + ": " + new String(message.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Delivery Complete!");
}
});
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
System.out.println("Connection Success!");
try {
System.out.println("Subscribing to /test");
mqttAndroidClient.subscribe("/test", 0);
System.out.println("Subscribed to /test");
System.out.println("Publishing message..");
mqttAndroidClient.publish("/test", new MqttMessage("Hello world testing..!".getBytes()));
} catch (MqttException ex) {
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
System.out.println("Connection Failure!");
System.out.println("throwable: " + exception.toString());
}
});
} catch (MqttException ex) {
System.out.println(ex.toString());
}
}
}
I've tried using different ports but the error is same. Can anyone help what am i doing wrong?
As you are getting started, you need to see see how different implementations work. Take a look at my implementation. I use a separated class for MQTT specific stuff.
MqttUtil.java
public class MqttUtil {
private static final String MQTT_TOPIC = "test/topic";
private static final String MQTT_URL = "tcp://localhost:1883";
private static boolean published;
private static MqttAndroidClient client;
private static final String TAG = MqttUtil.class.getName();
public static MqttAndroidClient getClient(Context context){
if(client == null){
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(context, MQTT_URL, clientId);
}
if(!client.isConnected())
connect();
return client;
}
private static void connect(){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setKeepAliveInterval(30);
try{
client.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d(TAG, "onSuccess");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG, "onFailure. Exception when connecting: " + exception);
}
});
}catch (Exception e) {
Log.e(TAG, "Error while connecting to Mqtt broker : " + e);
e.printStackTrace();
}
}
public static void publishMessage(final String payload){
published = false;
try {
byte[] encodedpayload = payload.getBytes();
MqttMessage message = new MqttMessage(encodedpayload);
client.publish(MQTT_TOPIC, message);
published = true;
Log.i(TAG, "message successfully published : " + payload);
} catch (Exception e) {
Log.e(TAG, "Error when publishing message : " + e);
e.printStackTrace();
}
}
public static void close(){
if(client != null) {
client.unregisterResources();
client.close();
}
}
}
And you can simply use it in your HomeActivity. Check it below:
public class HomeActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get Mqtt client singleton instance
MqttUtil.getClient(this);
// Publish a sample message
MqttUtil.publishMessage("Hello Android MQTT");
}
}
For testing purposes, use your Mosquitto sub client and see if you get the message.
Hope that helps!
try using port 8883
String clientId = MqttClient.generateClientId();
final MqttAndroidClient client =
new MqttAndroidClient(this.getApplicationContext(), "ssl://iot.eclipse.org:8883",
clientId);
try {
MqttConnectOptions options = new MqttConnectOptions();
InputStream input =
this.getApplicationContext().getAssets().open("iot.eclipse.org.bks");
options.setSocketFactory(client.getSSLSocketFactory(input, "eclipse-password"));
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d(TAG, "onSuccess");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d(TAG, "onFailure");
}
});
} catch (MqttException | IOException e) {
e.printStackTrace();
}
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();
}
}