I am trying to run the below code I am getting EOFException. The below is my output
Connected to ssl://REMOVED.messaging.internetofthings.ibmcloud.com:8883
.deliveryComplete() entered
Data published on topic iot-2/type/loradevice/id/cdef1234/cmd/cid/fmt/json and the msg is{"count":0,"cmd":"reset","time":"2017-01-25 18:38:34"}
connection true
Connection lost (32109) - java.io.EOFException
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:146)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.EOFException
at java.io.DataInputStream.readByte(DataInputStream.java:267)
at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:65)
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:107)
... 1 more
The code is below
package com.ibm.bluemixmqtt;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.json.JSONException;
import org.apache.commons.json.JSONObject;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
public class AppTest2
{
private MqttHandler1 handler;
/**
* #param args
*/
public static void main(String[] args)
{
new AppTest2().doApp();
}
/**
* Run the app
*/
public void doApp()
{
// Read properties from the conf file
Properties props = MqttUtil.readProperties("Mydata\\app.conf");
String org = "REMOVED";
String id = "REMOVED";
String authmethod = "REMOVED";
String authtoken = "REMOVED";
// isSSL property
String sslStr = props.getProperty("isSSL");
boolean isSSL = false;
if (sslStr.equals("T")) {
isSSL = true;
}
System.out.println("org: " + org);
System.out.println("id: " + id);
System.out.println("authmethod: " + authmethod);
System.out.println("authtoken" + authtoken);
System.out.println("isSSL: " + isSSL);
// Format: a:<orgid>:<app-id>
String clientId = "a:" + org + ":" + id;
String serverHost = org + MqttUtil.SERVER_SUFFIX;
handler = new MqttHandler1();
handler.connect(serverHost, clientId, authmethod, authtoken, isSSL);
publish();
}
public void publish(){
JSONObject jsonObj = new JSONObject();
String deviceid = "cdef1234";
try {
jsonObj.put("cmd", "reset");
jsonObj.put("count", 0);
jsonObj.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
} catch (JSONException e) {
e.printStackTrace();
}
handler.publish(
"iot-2/type/" + MqttUtil.DEFAULT_DEVICE_TYPE + "/id/" + deviceid + "/cmd/" + MqttUtil.DEFAULT_CMD_ID + "/fmt/json",
jsonObj.toString(), false, 0);
}
}
class MqttHandler1 implements MqttCallback
{
private final static String DEFAULT_TCP_PORT = "1883";
private final static String DEFAULT_SSL_PORT = "8883";
private MqttClient client = null;
public MqttHandler1()
{
}
#Override
public void connectionLost(Throwable throwable)
{
if (throwable != null) {
System.out.println("Error3");
throwable.printStackTrace();
}
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken)
{
System.out.println(".deliveryComplete() entered");
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception
{
String payload = new String(mqttMessage.getPayload());
System.out.println(".messageArrived - Message received on topic " + topic + ": message is " + payload);
}
public void connect(String serverHost, String clientId, String authmethod, String authtoken, boolean isSSL)
{
// check if client is already connected
if (!isMqttConnected()) {
String connectionUri = null;
// tcp://<org-id>.messaging.internetofthings.ibmcloud.com:1883
// ssl://<org-id>.messaging.internetofthings.ibmcloud.com:8883
if (isSSL) {
connectionUri = "ssl://" + serverHost + ":" + DEFAULT_SSL_PORT;
} else {
connectionUri = "tcp://" + serverHost + ":" + DEFAULT_TCP_PORT;
}
if (client != null) {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
client = null;
}
try {
client = new MqttClient(connectionUri, clientId);
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(this);
// create MqttConnectOptions and set the clean session flag
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setUserName(authmethod);
options.setPassword(authtoken.toCharArray());
options.setKeepAliveInterval(2000);
// If SSL is used, do not forget to use TLSv1.2
if (isSSL) {
java.util.Properties sslClientProps = new java.util.Properties();
sslClientProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
options.setSSLProperties(sslClientProps);
}
try {
// connect
client.connect(options);
System.out.println("Connected to " + connectionUri);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
public void disconnect()
{
// check if client is actually connected
if (isMqttConnected()) {
try {
// disconnect
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
public void subscribe(String topic, int qos)
{
// check if client is connected
if (isMqttConnected()) {
try {
client.subscribe(topic, qos);
System.out.println("Subscribed: " + topic);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
connectionLost(null);
}
}
public void unsubscribe(String topic)
{
// check if client is connected
if (isMqttConnected()) {
try {
client.unsubscribe(topic);
} catch (MqttException e) {
e.printStackTrace();
}
} else {
connectionLost(null);
}
}
public void publish(String topic, String message, boolean retained, int qos)
{
// check if client is connected
if (isMqttConnected()) {
// create a new MqttMessage from the message string
MqttMessage mqttMsg = new MqttMessage(message.getBytes());
// set retained flag
mqttMsg.setRetained(retained);
// set quality of service
mqttMsg.setQos(qos);
try {
client.publish(topic, mqttMsg);
System.out.println("Data published on topic " + topic + " and the msg is" + mqttMsg);
System.out.println("connection "+client.isConnected());
} catch (MqttPersistenceException e) {
System.out.println("Error1");
e.printStackTrace();
} catch (MqttException e) {
System.out.println("Error1");
e.printStackTrace();
}
} else {
connectionLost(null);
}
}
private boolean isMqttConnected()
{
boolean connected = false;
try {
if ((client != null) && (client.isConnected())) {
connected = true;
}
} catch (Exception e) {
// swallowing the exception as it means the client is not connected
}
return connected;
}
}
Any one help me on this.
Thanks in adavance.
the EOFException might indicates that the clientID is reused and the access is blocked... make sure that you only call once the connect method... possibly use only the SSL or non-SSL connection sequence
Related
I have a simple rmi-server and rmi-client. When i run this server and client in same network, my server function returns the result properly. But my server and client are in different networks and if the process time is more than 3-4 minutes client can not get the result, although server fihishes the operation.
here is my entire server code:
public class SimpleServer {
ServerRemoteObject mRemoteObject;
public static int RMIInPort = 27550;
public static int delay = 0;
public byte[] handleEvent(byte[] mMessage) throws Exception {
String request = new String(mMessage, "UTF-8");
// if ("hearthbeat".equalsIgnoreCase(request)) {
// System.out.println("returning for hearthbeat");
// return "hearthbeat response".getBytes("UTF-8");
// }
System.out.println(request);
Thread.sleep(delay);
System.out.println("returning response");
return "this is response".getBytes("UTF-8");
}
public void bindYourself(int rmiport) {
try {
mRemoteObject = new ServerRemoteObject(this);
java.rmi.registry.Registry iRegistry = LocateRegistry.getRegistry(rmiport);
iRegistry.rebind("Server", mRemoteObject);
} catch (Exception e) {
e.printStackTrace();
mRemoteObject = null;
}
}
public static void main(String[] server) {
int rmiport = Integer.parseInt(server[0]);
RMIInPort = Integer.parseInt(server[1]);
delay = Integer.parseInt(server[2]);
System.out.println("server java:" + System.getProperty("java.version"));
System.out.println("server started on:" + rmiport + "/" + RMIInPort);
System.out.println("server delay on:" + delay);
SimpleServer iServer = new SimpleServer();
iServer.bindYourself(rmiport);
while (true) {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and here is my client code:
public class SimpleClient {
ISimpleServer iServer;
public SimpleClient(String p_strServerIp, String p_strCMName, int nRMIPort) {
try {
if (nRMIPort == 1099) {
iServer = (ISimpleServer) Naming.lookup("rmi://" + p_strServerIp + "/" + p_strCMName);
} else {
Registry rmiRegistry = null;
rmiRegistry = LocateRegistry.getRegistry(p_strServerIp, nRMIPort);
iServer = (ISimpleServer) rmiRegistry.lookup(p_strCMName);
}
} catch (Exception ex) {
ex.printStackTrace();
iServer = null;
}
}
public static void main(String... strings) {
String ip = strings[0];
int rmiport = Integer.parseInt(strings[1]);
System.out.println("client java:" + System.getProperty("java.version"));
System.out.println("client is looking for:" + ip + ":" + rmiport);
SimpleClient iClient = new SimpleClient(ip, "Server", rmiport);
try {
byte[] response = iClient.iServer.doaction("this is request".getBytes("UTF-8"));
System.out.println(new String(response, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here is my rmi-registry code:
public class SimpleRMI implements Runnable {
Registry mRegistry = null;
public SimpleRMI(int nPort) {
try {
mRegistry = new sun.rmi.registry.RegistryImpl(nPort);
} catch (RemoteException e1) {
e1.printStackTrace();
}
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(360000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String... strings) {
int rmiport = Integer.parseInt(strings[0]);
System.out.println("rmi java:" + System.getProperty("java.version"));
System.out.println("rmi started on:" + rmiport);
SimpleRMI iRegisry = new SimpleRMI(rmiport);
Thread tThread = new Thread(iRegisry);
tThread.start();
byte[] bytes = new byte[1];
while (true) {
try {
System.in.read(bytes);
if (bytes[0] == 13) {
try {
iRegisry.listRegistry();
} catch (Exception exc2) {
exc2.printStackTrace();
}
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
private void listRegistry() {
String[] strList = null;
try {
strList = mRegistry.list();
if (strList != null) {
for (int i = 0; i < strList.length; i++) {
int j = i + 1;
String name = strList[i];
java.rmi.Remote r = mRegistry.lookup(name);
System.out.println(j + ". " + strList[i] + " -> "
+ r.toString());
}
}
System.out.println();
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
and my remote interface and remote object:
public interface ISimpleServer extends java.rmi.Remote {
public byte[] doaction(byte[] message) throws java.rmi.RemoteException;
}
#SuppressWarnings("serial")
public class ServerRemoteObject extends UnicastRemoteObject implements ISimpleServer {
SimpleServer Server = null;
public ServerRemoteObject(SimpleServer pServer) throws RemoteException {
super(SimpleServer.RMIInPort);
Server = pServer;
}
#Override
public byte[] doaction(byte[] message) throws RemoteException {
try {
return Server.handleEvent(message);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
when i run client and server in different networks. (i run client in my home network) and if delay is more than 3-4 mins server prints returning response but client still waits for the response. If delay is only 1 minute, clients gets the result properly.
Can you please help me to find where the problem is?
This is the piece of code I am facing issues with. When the post construct gets called..the source gets set .. But when I receive a message from server and the processBinaryMessage method gets called..the source turns out to be null.
I don't understand the problem...Any help is appreciated..
#ClientEndpoint
#Component
public class MyClientEndpoint {
#Inject
private Source Source;
private boolean postConstructCalled = false;
#PostConstruct
public void init() {
postConstructCalled = true;
System.out.println("Post construct called ... ");
}
#OnOpen
public void onOpen(Session session) {
System.out.println("Connected to endpoint: " + session.getBasicRemote());
SessionUtil.setSession(session);
try {
System.out.println("Checking the established connection........");
session.getBasicRemote().sendText("Checking the connection...");
} catch (IOException ex) {
Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
}
}
#OnMessage
public void processMessage(String message) {
System.out.println("Received string message in client: " + message);
}
#OnMessage
public void processBinaryMessage(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
byte[] type = new byte[3];
byteBuffer.get(type);
String msgType = new String(type);
//System.out.println("Read type : " + msgType);
if(msgType.compareTo("MAX") == 0) {
int maxLimit = byteBuffer.getInt();
System.out.println("Read max blocks : " + maxLimit);
ClientDataTransfer.setMaxTransferLimit(maxLimit);
}
else if(msgType.compareTo("NXT") == 0) {
ClientDataTransfer.incMaxTransferLimit();
}
else if(msgType.compareTo("MAP") == 0) {
int length = byteBuffer.getInt();
byte[] data = new byte[length];
byteBuffer.get(data);
source.getClientDataTransfer().addToDataRequestQueue(data);
}
}
#OnError
public void processError(Throwable t) {
t.printStackTrace();
}
#OnClose
public void onClose(Session session) {
try {
session.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Closing connection to endpoint: " + session.getBasicRemote());
}
}
Thanks,
Sreeja
I have to retrieve offline messages from Google Talk for a particular client (friend/ XMPP Client) with whom I have had a conversationn with.
Additionally, I want to retrieve the chat history.
Right now, I am using a Hash Map to keep track of the conversation and have no means of having the offline messages.
I have made an XMPP connection to "talk.google.com". I am currently able to send messages to the client via my console. I have implemented the Message Listener Interface and hence can receive messages in my console itself.
I have another implementaion(made use of OfflineMessageManager) where I try to extract the offline messages headers as a start, unfortunately, it fails with Null Exception.
I have used smack-tcp version 4.0.3 and smackx 3.1.0.
Please find below what I have tried till now...
Working Implementation:
public class StartChatImpl implements startChat, MessageListener {
static XMPPConnection myXMPPConnection;
static ArrayList<String> myFriends = new ArrayList<String>();
ArrayList<Msg> messages;
HashMap<String,ArrayList> conversation = new HashMap<String, ArrayList>();
OfflineMessageManager offlineMessages;
#Override
public void engageChat(ChatRequest chatRequest) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true);
myXMPPConnection = new XMPPTCPConnection(config);
try{
System.out.println("Connecting to talk.google.com");
myXMPPConnection.connect();
System.out.println("Logging you in...");
myXMPPConnection.login(chatRequest.getUsername(),chatRequest.getPassword());
Presence pres = new Presence(Presence.Type.unavailable);
myXMPPConnection.sendPacket(pres);
offlineMessages = new OfflineMessageManager(myXMPPConnection);
System.out.println("You have been successfully connected.");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send (String message, String to) throws XMPPException
{
Chat chat = ChatManager.getInstanceFor(myXMPPConnection).createChat(to, this);
//System.out.println("********************************************");
//System.out.println("CHAT ID: "+ chat.getThreadID());
//System.out.println("Participant: "+chat.getParticipant());
//System.out.println("********************************************");
try {
chat.sendMessage(message);
String friendName = myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName();
if(conversation.containsKey(friendName))
{
messages = conversation.get(friendName);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
message = "bot says: "+message;
Msg actualMsg = new Msg(currentTimestamp,message,"bot");
messages.add(actualMsg);
//messages.add("bot says: "+message);
}
else
{
messages = new ArrayList<Msg>();
//messages.add("Bot initiated the conversation on: "+new Date());
//messages.add("bot says: "+message);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
message = "bot says: "+message;
Msg actualMsg = new Msg(currentTimestamp,message,"bot");
messages.add(actualMsg);
conversation.put(friendName,messages);
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
System.out.println("You said "+"'"+message+"'"+" to "+myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName());
}
PacketListener myPacketListener = new PacketListener() {
#Override
public void processPacket(Packet p) {
if (p instanceof Message) {
Message msg = (Message) p;
}
}
};
public void displayMyFriends()
{
Roster roster = myXMPPConnection.getRoster();
Collection entries = roster.getEntries();
System.out.println("You currently have: "+entries.size()+" friends available to chat.");
int counter = 0;
Iterator i = entries.iterator();
while(i.hasNext())
{
RosterEntry r = (RosterEntry) i.next();
Presence.Type entryPresence;
entryPresence = roster.getPresence(r.getUser()).getType();
System.out.println((counter+1)+" . "+r.getName() +" is "+entryPresence);
//System.out.println("id:..."+r.getUser());
myFriends.add(r.getUser());
counter++;
}
}
public void disconnectMe()
{
try {
System.out.println("Disconnection in progress...");
myXMPPConnection.disconnect();
System.out.println("You have been successfully disconnected.");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
#Override
public void processMessage(Chat chat, Message message)
{
if((message.getType() == Message.Type.chat) && (message.getBody()!= null)) {
System.out.println(myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName() + " says: " + message.getBody());
String myMsg = myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName() + " says: " + message.getBody();
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
Msg actualMsg = new Msg(currentTimestamp,myMsg,"customer");
conversation.get(myXMPPConnection.getRoster().getEntry(chat.getParticipant()).getName()).
add(actualMsg);
}
}
public void receiveMessage(){
myXMPPConnection.addPacketListener(myPacketListener, null);
}
public void retrieveUnservicedMessagesForSpecificPerson(String clientName)
{
ArrayList<Msg> myMessages = conversation.get(clientName);
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
System.out.println("Unserviced messages from: "+ clientName);
if(!myMessages.isEmpty())
{
int counter = myMessages.size()-1;
System.out.println("Size of array list: "+counter);
boolean found = false;
java.sql.Timestamp lastBotTimestamp = null;
while (counter != 0 && found == false){
if(myMessages.get(counter).getOwner()=="bot")
{
lastBotTimestamp = myMessages.get(counter).getTimestamp();
found = true;
}
else
{
counter = counter-1;
}
}
for(Msg msg:myMessages)
{
if(msg.getTimestamp().before(currentTimestamp) &&
msg.getTimestamp().after(lastBotTimestamp)){
System.out.println("---------------------------");
System.out.println("-"+msg.getActualMessage());
System.out.println("-"+msg.getTimestamp());
System.out.println("---------------------------");
}
}
}
}
public void returnConversation(String name) {
System.out.println("Name of participant entered: "+ name);
System.out.println("Conversation history is: ");
ArrayList<Msg> m = conversation.get(name);
for(Msg msg:m){
System.out.println(msg.getActualMessage());
System.out.println("on: "+msg.getTimestamp());
}
}
public void returnAllUnservicedMessagesHistory()
{
for(String name: conversation.keySet())
{
System.out.println("History of unserviced messages for: "+ name);
retrieveUnservicedMessagesForSpecificPerson(name);
}
}
public void getOfflineMessagesCount(){
try {
System.out.println("Number of offline messages: "+ offlineMessages.getMessageCount());
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
My Main Class Implementation:
public class MainGoogleChatApp {
public static void main(String[] args)
{
//Step 1: need to make a chat request with your username and password.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your username to start: ");
String myUsername = input.next();
System.out.println("Please enter your password to continue: ");
String myPassword = input.next();
ChatRequest myChatRequest = new ChatRequest();
myChatRequest.setUsername(myUsername);
myChatRequest.setPassword(myPassword);
//Step 2: Need to initiate a connection to talk.google.com
StartChatImpl convo = new StartChatImpl();
try {
convo.engageChat(myChatRequest);
} catch (XMPPException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String myMessage;
System.out.println("Friend list.");
convo.displayMyFriends();
convo.receiveMessage();
try {
while(true)
{
System.out.println("Input Which friend you want to chat with '0 to sign out' : ");
int num = input.nextInt() -1;
if (num == -1){
break;
}
String chatWith = StartChatImpl.myFriends.get(num);
System.out.print("Type your message: ");
myMessage=br.readLine();
try {
convo.send(myMessage,chatWith);
} catch (XMPPException e) {
e.printStackTrace();
}
convo.displayMyFriends();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Enter participant name to get specific chat...");
String yourName = null;
try {
yourName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("/./././././././././././././..//.");
if(yourName!=null){
System.out.println("Your name is not null...ok");
convo.returnConversation(yourName);
}
System.out.println("Enter another participant's name to get specific chat...");
String yourName1 = null;
try {
yourName1 = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("/./././././././././././././..//.");
if(yourName1!=null){
System.out.println("Your name is not null...ok");
convo.returnConversation(yourName1);
}
System.out.println("Select a client name for whom you want to view unserviced messages: ");
String yourClientName = null;
try {
yourClientName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if(yourClientName!=null){
System.out.println("...........................................");
convo.retrieveUnservicedMessagesForSpecificPerson(yourClientName);
}
System.out.println("...........................................");
convo.returnAllUnservicedMessagesHistory();
System.out.println("You have chosen to disconnect yourself from talk.google.com");
convo.disconnectMe();
System.exit(0);
}
}
Attempt to retrieve offline messages headers:
public class TestOfflineService {
XMPPConnection xmppConnection = null;
//OfflineMessageManager offlineMessageManager = null;
public void makeConnection()
{
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setSendPresence(true);
xmppConnection = new XMPPTCPConnection(config);
try{
System.out.println("Connecting to talk.google.com");
xmppConnection.connect();
System.out.println("Logging you in...");
xmppConnection.login("*******.*#***.com", "*****");
System.out.println("You have been successfully connected.");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
public void makeMeUnavailable()
{
try {
xmppConnection.sendPacket(new Presence(Presence.Type.unavailable));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
public void getOfflineMessages()
{
OfflineMessageManager offlineMessageManager1 = new OfflineMessageManager(xmppConnection);
try {
Iterator<OfflineMessageHeader> headers = offlineMessageManager1.getHeaders();
if(headers.hasNext())
{
System.out.println("Messages found");
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
TestOfflineService test = new TestOfflineService();
test.makeConnection();
test.makeMeUnavailable();
System.out.println("Enter messages");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Getting offline messages.....");
test.getOfflineMessages();
}
}
OfflineMessageManager tries to use XEP-0013 to retrieve offline messages. This XEP isn't implemented by GTalk. Also note that ever starting Hangouts means you'll never get offline messages anymore, as the Hangouts instance is never offline.
GTalk also does not have an XMPP API to retrieve chat history, like XEP-0136 or XEP-0313.
As part of my lab this week I am suppose to convert a socket based chat application to RMI. So far I managed to connect server and client together and transfer data between them but the transfer is not continuous. What I mean is that when the client first connects t the server it broadcasts a message "X has entered the conversation" but that is all. Anything I type after that wont get broadcasted. I am about to pull out my hair. Please help.
public class ChatServer extends UnicastRemoteObject implements ChatMessage {
private static final long serialVersionUID = 1L;
private String sender;
private String message;
private ChatMessageType t;
public ChatServer() throws RemoteException {
super();
}
#Override
public void Message(String sender, ChatMessageType t, String message)
throws RemoteException {
this.sender = sender;
this.message = message;
this.t = t;
}
#Override
public String getSender() throws RemoteException {
return sender;
}
#Override
public String getMessage() throws RemoteException {
return message;
}
#Override
public ChatMessageType getType() throws RemoteException {
return t;
}
public String ToString() throws RemoteException{
String strMessage;
switch (t) {
case SETUP:
strMessage = sender + " has entered the conversation.";
break;
case TEARDOWN:
strMessage = sender + " has left the conversation.";
break;
case MESSAGE:
strMessage = sender + ": " + message;
break;
default:
strMessage = "";
}
return strMessage;
}
// driver.
public static void main(String arg[]) {
try {
ChatServer c = new ChatServer();
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("Server", c);
System.out.println("Server bound in registry");
} catch (Exception e) {
System.out.println("Server error: " + e.getMessage());
e.printStackTrace();
}
}
}
public class ChatClient implements ActionListener {
// static private Socket c;
static ChatMessage obj = null;
// static private ObjectInputStream in;
// static private ObjectOutputStream out;
static private String name;
static private String host;
static private Integer port;
/**
* Launches this application
*/
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (args.length != 3) {
System.out
.println("Client requires exactly three args to run.");
System.exit(-1);
}
name = args[0];
host = args[1];
port = new Integer(args[2]);
final ChatClient application = new ChatClient();
application.getJFrame().setVisible(true);
try {
System.out.println("client: connecting to server...");
// c = new Socket(host, port);
obj = (ChatMessage) Naming.lookup("//" + host + ":" + port
+ "/Server");
System.out.println("client: connected!");
} catch (Exception e) {
System.out.println("client: " + e.getMessage());
System.exit(-1);
}
try {
// out = new ObjectOutputStream(c.getOutputStream());
// in = new ObjectInputStream(c.getInputStream());
// announce to other clients that you're here
// out.writeObject(new ChatMessage(name,
// ChatMessageType.SETUP, ""));
obj.Message(name, ChatMessageType.SETUP, "");
} catch (Exception e) {
}
// set up the client's listener as an anonymous thread that's
// always running
// new Thread(new Runnable(){
// public void run()
// {
// while(true)
// {
try {
System.out.println(name + ": waiting for data");
ChatMessage m = (ChatMessage) Naming.lookup("//" + host
+ ":" + port + "/Server");
System.out.println(name + ": data received");
application.updateTextArea(m.ToString());
} catch (Exception e) {
}
// }
// }
// }).start();
}
});
}
public void updateTextArea(final String message) {
conversation.setText(conversation.getText() + message + "\n");
// this will guarantee that the bottom of the conversation is visible.
conversation.setCaretPosition(conversation.getText().length());
}
// send button has been pressed, send the message to the server.
public void actionPerformed(ActionEvent e) {
if (send.getText().equals("Send")) {
try {
System.out.println(name + ": sending data");
// ChatMessage m = new ChatMessage(name,
// ChatMessageType.MESSAGE, message.getText());
// out.writeObject(m);
obj.Message(name, ChatMessageType.MESSAGE, message.getText());
message.setText(""); // clear the text box.
System.out.println(name + ": data sent");
} catch (Exception ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
}
}
enum ChatMessageType{
SETUP,
MESSAGE,
TEARDOWN
}public interface ChatMessage extends Remote{
public String getSender() throws RemoteException;
public String getMessage() throws RemoteException;
public ChatMessageType getType() throws RemoteException;
public void Message(String sender, ChatMessageType t, String message) throws RemoteException;
public String ToString() throws RemoteException;
I realize this question is pretty old and you probably figured out an answer for this, but, I thought I'd share an approach I took for going from Java sockets to RMI. Maybe it is useful for others looking to do the same thing.
I basically abstracted out the socket portion into a "Tunnel" object that represents a communication path between hosts. And the tunnel consists of several "channels", that represent a one-way communication between the source and destination.
You can check out more details at my blog here: http://www.thecodespot.com/?p=1
I have written a mqtt client using paho mqttv3
This is the code for the client:
public class MQTT_Client {
private MqttClient mqtt;
private MqttConnectOptions conOpt;
private static Logger log = Logger.getRootLogger();
private String topicFilter;
private int connectionTimeout = 30;
public MQTT_Client(String brokerUrl) {
this.topicFilter = "/bmpiips/+/hb/out";
try {
String clientId = "HBA";
mqtt = new MqttClient(brokerUrl, clientId, new MemoryPersistence());
log.info("Connecting to " + brokerUrl + " with client ID " + mqtt.getClientId());
conOpt = new MqttConnectOptions();
conOpt.setCleanSession(true);
mqtt.setCallback(new MQTT_Callback(this));
} catch (MqttException e) {
log.error(null, e);
}
}
public void start() {
reconnect();
try {
subscribe(topicFilter, 1);
} catch (MqttException e) {
log.warn("Unable to subscribe to " + topicFilter);
}
}
private void connect() throws MqttSecurityException, MqttException {
if (mqtt.isConnected() == false) {
mqtt.connect(conOpt);
if (mqtt.isConnected() == true) {
log.info("Connected to MQTT Broker.");
}
}
}
public boolean isConnected() {
return mqtt.isConnected();
}
public boolean publish(String topicName, byte[] payload, int qos) {
try {
MqttTopic topic = mqtt.getTopic(topicName);
MqttMessage message = new MqttMessage(payload);
message.setQos(qos);
log.info("Publishing to topic: \"" + topicName + "\" Message size: " + payload.length + " bytes");
MqttDeliveryToken token = topic.publish(message);
token.waitForCompletion();
return true;
} catch (MqttException e) {
log.error(null, e);
return false;
}
}
public void subscribe(String topicName, int qos) throws MqttSecurityException, MqttException {
mqtt.subscribe(topicName, qos);
log.info("Subscribed to topic \"" + topicName + "\"");
}
public void reconnect() {
if (mqtt.isConnected() == false) {
try {
connect();
} catch (MqttSecurityException e) {
log.error("Coud not reconnect...", e);
} catch (MqttException e) {
log.error("Coud not reconnect...", e);
}
} else {
log.error("Allready connected...");
}
}
public void disconnect() throws MqttException {
mqtt.disconnect();
while (mqtt.isConnected()) {
// wait for disconnection
}
if (mqtt.isConnected() == false) {
log.info("Disconnected from the MQTT Broker.");
}
}
public String getTopicFilter() {
return topicFilter;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
}
and this is the code for the callback class:
public class MQTT_Callback implements MqttCallback {
private static Logger log = Logger.getRootLogger();
private static MQTT_ThreadPool threadPool = new MQTT_ThreadPool();
private final MQTT_Client mqtt;
public MQTT_Callback(MQTT_Client mqtt) {
this.mqtt = mqtt;
}
#Override
public void connectionLost(Throwable cause) {
log.error("Disconnected from MqttBroker", cause);
while (mqtt.isConnected() == false) {
try {
log.info("Sleeping for : " + mqtt.getConnectionTimeout() + " seconds...");
Thread.sleep(mqtt.getConnectionTimeout() * 1000);
} catch (InterruptedException e) {
log.error("Coud not sleep...");
}
mqtt.reconnect();
try {
mqtt.subscribe(mqtt.getTopicFilter(), 1);
} catch (MqttException e) {
log.error(e);
}
}
}
#Override
public void deliveryComplete(MqttDeliveryToken token) {
log.info("Message delivered successfully");
}
#Override
public void messageArrived(MqttTopic topic, MqttMessage message) throws Exception {
log.info("Message received from topic: " + topic.getName() + " Message size: " + message.getPayload().length
+ " bytes");
threadPool.execute(topic, message);
}
}
It works ok but from time to time I get a weird exception that kills the connection:
2013-07-09 10:36:05.959 ERROR root:23 - Disconnected from MqttBroker
Connection lost (32109) - java.io.EOFException
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:119)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.EOFException
at java.io.DataInputStream.readByte(Unknown Source)
at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:51)
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:86)
... 1 more
If anyone has ever come across this please give me some tips.