Question: How to start ! Help me and other newbies

Hi @ll.

At first I want to mention, that my english isn’'t the best so I hope that all of you will understand my problem.

I want to code a simple communication between UserA and UserB.

UserA should be able to send a message to UserB, while UserB is waiting for the message.

So really simple…

But it doesnt work !

I searched for about 5 hours in the forum but there wasnt any good solution.

It would be very nice if someone could post code so that other beginners can start

easily…

Thanks

My Code:

UserA:


import java.io.IOException;

import org.jivesoftware.smack.Chat;

import org.jivesoftware.smack.XMPPConnection;

import org.jivesoftware.smack.XMPPException;

import com.sun.jmx.snmp.Timestamp;

public class My_Test

{

public static void main(String argc[]) throws IOException

{

My_Test obj = new My_Test();

//Parameter

String host = “rsiegert-ws”;

int port = 5222;

String username = “USERNAME”;

String password = “PASSWORD”;

Timestamp tms = new Timestamp();

long l = tms.getDateTime();

System.out.println(l);

//BENUTZERNAME anmelden

XMPPConnection con = obj.Connect(host,port,username,password);

//BENUTZERNAME schickt “test”

obj.SendMessage(con,“test”);

con.close();

System.out.println(“Ende !”);

}

/**

  • @param host

  • @param port

  • @param username

  • @param password

  • @return

*/

XMPPConnection Connect(String host,int port,String username,String password)

{

try

{

XMPPConnection con = new XMPPConnection(host,port);

con.login(username,password);

System.out.println(“Connected !”);

return con;

}

catch(XMPPException XMPPe)

{

System.out.println("Fehler : "+XMPPe);

return null;

}

}

/**

  • @param con

  • @param message

*/

void SendMessage(XMPPConnection con,String message)

{

try

{

Chat newChat = con.createChat(“1@rsiegert-ws”);

newChat.sendMessage(message);

System.out.println(“Message sent !”);

}

catch(Exception e){System.out.println(e);}

}

}

/code



UserB:

import org.jivesoftware.smack.Chat;

import org.jivesoftware.smack.XMPPConnection;

import org.jivesoftware.smack.XMPPException;

import org.jivesoftware.smack.packet.Message;

public class Wartender

{

public static void main(String argc[]) throws XMPPException

{

Wartender wart = new Wartender();

wart.StartWartender();

}

void StartWartender()

{

String host = “rsiegert-ws”;

int port = 5222;

String username = “1”;

String password = “1”;

XMPPConnection con = Connect(host,port,username,password);

Listen(con);

System.out.println(“Ende”);

}

/**

  • @param host

  • @param port

  • @param username

  • @param password

  • @return

*/

XMPPConnection Connect(String host,int port,String username,String password)

{

try

{

XMPPConnection con = new XMPPConnection(host,port);

con.login(username,password);

System.out.println(“Connected !”);

return con;

}

catch(XMPPException XMPPe)

{

System.out.println("Fehler : "+XMPPe);

return null;

}

}

/**

  • Wartet auf Timestamp vom “Client”

  • @param con

  • @throws XMPPException

*/

void Listen(XMPPConnection conn2)

{

Chat newChat = conn2.createChat(“USERNAME@rsiegert-ws”);

while (true) {

// Wait for the next message the user types to us.

System.out.println(“Waiting…”);

Message message = newChat.nextMessage();

System.out.println("Got it ! : "+message.getBody());

// Send back the same text the other user sent us.

}

}

}

/code


Message was edited by: Khaled83

For some reason I never found Chat#nextMessage a great way of obtaining a message sent from user to user.

Far better imo to attach a MessageListener to the connection and listen out for Message Packets as they come in.

Something like this

class MessageListener implements PacketListener {

void processPacket(Packet packet) {

Message message = (Message)packet;

Message.Type messageType = message.getType();

if(messageType == Message.Type.CHAT) {

System.out.println("Message From: " + message.getFrom());

System.out.println("Message Body; " + message.getBody());

}

}

class Connect {

public static void main(String [] args) {

// handle connection here

// after your connection but before you login attach your listener to

// the connection

// you need a filter as well

PacketFilter filter = new MessageTypeFilter(Message.class);

// add the listener and the filter to the connection

conn.addPacketListener(new MessageListener(), filter);

// login here

}

}

/code

hth

Jon

JonWright thank you very much for your quick reply.

I changed now my code and removed the nextMessage() - method.

Looks now like this:


import org.jivesoftware.smack.XMPPConnection;

import org.jivesoftware.smack.filter.MessageTypeFilter;

import org.jivesoftware.smack.filter.PacketFilter;

import org.jivesoftware.smack.packet.Message;

public class test {

public static void main(String [] args) {

// handle connection here

try

{

XMPPConnection con = new XMPPConnection(“rsiegert-ws”,5222);

System.out.println(“Connected !”);

// after your connection but before you login attach your listener to

// the connection

// you need a filter as well

PacketFilter filter = new MessageTypeFilter(Message.Type.NORMAL);

// add the listener and the filter to the connection

con.addPacketListener(new MessageListener(), filter);

// login here

Thread.sleep(15000);

con.login(“2”,“2”);

}

catch(Exception XMPPe)

{

System.out.println("Fehler : "+XMPPe);

}

}

}


Now I expected that a LISTENER waits till a new message will arrive for the logged in user, like the nextMessage()-Method.

Do I have to add a endles-loop after the login or something like that ?

Sorry if the questions sounds stupid, but I’'m really a little bit confused

Would be very nice if someone (JonWright ? ) could post a functionable code for:

A sending message to B

B is receiving the message and prints the body

Thank you

Regards from Frankfurt / Germany

After you login and are successfully authenticated with the Server just put an a

while(true) {} in the code

This will loop forever (until you hit ctrl+c).

Next grab another XMPP Client, Spark or Pandion will both do fine, and send a message to your logged in client. You should see the message printed to the cmd window.

If not check the Debug window to find out if the packet is actually being received. From there, you should be able to work out how to send the message from your client.

Thank you very much !

It works now fine with my client.

I think I will make a german tutorial after I have done this job…would be nice for other users

Best regards

Khaled

Message was edited by: Khaled83

np, if you get stuck further feel free to post and I’'ll see if I can help.

A German tutorial would be a great idea

What I did was created 3 classes

main, client app and listener.

import java.awt.HeadlessException;

import java.util.Vector;

import javax.swing.JFrame;

/**

  • @author schwartz

*/

public class Main {

/** Creates a new instance of Main */

public Main() {

}

/**

  • @param args the command line arguments

*/

public static void main(String[] args) {

int SSLportNumber = 443;

if (args.length == 0 ){

System.out.print("Using default port "+SSLportNumber +System.getProperty(“line.separator”));

}else {

SSLportNumber = Integer.valueOf(args[0]);

System.out.print("Using port "+SSLportNumber +System.getProperty(“line.separator”));

}

//Start both Client and Server

startBoth(SSLportNumber);

}

public static void startBoth(final int SSLportNumber) {

final Vector messages = new Vector();

(new Thread() {

public void run() {

// SSLServer server = null;

// try {

// server = new SSLServer(SSLportNumber, messages);

// } catch (Exception ex) {

// System.out.println("Failed to start SSL Sever "+ex);

// }

// server.runServer();

Listen.runListen();

}

}).start();

(new Thread() {

public void run() {

try {

JFrame f = new JFrame(“mChat (Secure Peer-to-Peer Chat)”);

SSLPanel p = new SSLPanel(SSLportNumber, messages);

f.setContentPane§;

f.setBounds(200,200,400,250);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

} catch (HeadlessException ex) {

ex.printStackTrace();

} catch (Exception ex) {

ex.printStackTrace();

}

}

}).start();

}

}

/code

Client App:

…hear is how I sent when the send button is preseed…

private void sendMessageButtonActionPerformed(java.awt.event.ActionEvent evt) {

String IP_Address = IPAddress.getText();

String userName=“brown”;

try {

// SSLServerSocket serverSocket;

XMPPConnection.DEBUG_ENABLED = true;

// Create a normal connection to

// XMPPConnection connection = new XMPPConnection(“3.57.108.19”);

// Create an SSL connection

XMPPConnection connection = new SSLXMPPConnection(IP_Address);

connection.login(userName,“install”);

connection.createChat(“schwartz@”+IP_Address).sendMessage(messageInput.getText( ));

results.append(userName+": "+ messageInput.getText()+System.getProperty(“line.separator”));

messageInput.setText("");

} catch (XMPPException ex) {

ex.printStackTrace();

}

}

/code

then in the listen class I tried…

I still cant seem to get the listen class part to work right

import org.jivesoftware.smack.PacketCollector;

import org.jivesoftware.smack.PacketListener;

import org.jivesoftware.smack.SSLXMPPConnection;

import org.jivesoftware.smack.XMPPConnection;

import org.jivesoftware.smack.XMPPException;

import org.jivesoftware.smack.filter.MessageTypeFilter;

import org.jivesoftware.smack.filter.PacketFilter;

import org.jivesoftware.smack.packet.Message;

import org.jivesoftware.smack.packet.Packet;

/*

  • Listen.java
  • Created on March 2, 2006, 12:49 PM
  • To change this template, choose Tools | Template Manager

  • and open the template in the editor.

*/

/**

  • @author schwartz

*/

public class Listen {

/** Creates a new instance of Listen */

public Listen() {

}

public static void runListen() throws XMPPException{

String IP_Address = “3.57.108.19”;

String userName = “brown”;

XMPPConnection connection = null;

PacketFilter filter = new MessageTypeFilter(Message.Type.NORMAL);

connection = new SSLXMPPConnection(IP_Address);

while(true){

PacketCollector myCollector = connection.createPacketCollector(filter);

PacketListener myListener = new PacketListener(){

public void processPacket(Packet packet){

//do something with incoming packet here

Message message = (Message)packet;

Message.Type messageType = message.getType();

System.out.println("Message From: " + message.getFrom());

System.out.println("Message Body; " + message.getBody());

}

};

connection.addPacketListener(myListener, filter);

}

}

}

/code

Any suggestion to correct my listener …

Message was edited by: Firestart

Message was edited by: Firestart

Message was edited by: Firestart

from what I quickly read it looks like you are trying to add the packet listener to a null XMPPConnection object. I’'m not sure if that would work!

When you say your listener is not working can you give anymore details such as

: Error messages

: Stack Trace:

Have you checked the debug window to see if thet packets are being received by your client

Also when posting code in future if you stick it between / code tags it makes reading it much easier

with the while look in my pc get very slow…because when

run it:

Using default port 443

Exception in thread “Image Fetcher 0” java.lang.OutOfMemoryError: Java heap space

Exception in thread “Thread-0” java.lang.OutOfMemoryError: Java heap space

Exception in thread “Image Fetcher 0” java.lang.OutOfMemoryError: Java heap space

if I take the while loop out. and send a message my Spark client see it, I reply to it and the debuger shows that I get a message. However it doesnt seem to print it out.

So I guess I have two errors: error loop (heap space), second Message received according to debuger but not printed.

Modified code to remove null…

But I have figured it out…it was a threading issue (2 connection open).

Message was edited by: Firestart

These two classes will connect to an XMPP Server and print out a message sent to the logged in client:

The first class implements PacketListener to listen out for Message Packets of Type CHAT

import org.jivesoftware.smack.*;

import org.jivesoftware.smackx.*;

import org.jivesoftware.smack.packet.*;

import org.jivesoftware.smack.filter.*;

public class MessageListener implements PacketListener {

public void processPacket(Packet packet) {

Message message = (Message)packet;

Message.Type messageType = message.getType();

if(messageType == Message.Type.CHAT) {

System.out.println("Message From: " + message.getFrom());

System.out.println("Message Body: " + message.getBody());

}

}

}

/code

The 2nd is simply a tester class that creates a new connection, add the listener and then logs in. Once logged in it then runs forever.

I’'ve set Debug_Enabled to true to you can see the packets coming into the client.

import org.jivesoftware.smack.*;

import org.jivesoftware.smackx.*;

import org.jivesoftware.smack.packet.*;

import org.jivesoftware.smack.filter.*;

public class Connect {

private static XMPPConnection conn;

public static void main(String [] args) {

PacketTypeFilter filter = new PacketTypeFilter(Message.class);

try {

conn.DEBUG_ENABLED = true;

conn = new XMPPConnection(“your server here” , your port number here);

conn.addPacketListener(new MessageListener(), filter);

conn.login(“your username here”, “your password here”);

while(true) {

}

} catch(XMPPException e) {}

}

}

/code

If you then login to another Jabber client and send messages to the user logged in above they will appear in the cmd window.

hth but if you get stuck further please post back

Jon

I have gone to the elaborate replies u have given to the new starters on smack.

Using those guidlines i could start a working model for my project.

Can u please tell me is possible to develop a proxy chat server (whic will contain all the chat logic) using java servlet. Because this will help users to access the jabber server which sits behind a firewall kind of stuff.

I have taken cue from ur suggestion and deployed the model in tomcat which is being handled by the servlet. the chat client submits data to the servlet, which talks to the jabber using the model. however i am facing the problem of session, then manipulating the response object etc.

any suggestion…

Syed Taha Owais

It does beg the question though, what is the point of Chat.nextMessage() ? It’‘s mentioned in the docs as a way to get a message, but it doesn’'t work in all cases.

In my testing, if I have two smack clients using just Chat.sendMessage and Chat.nextMessage, and both do sends and then receives, neither side ever returns from nextMessage (though the debug window shows that the message did at least get to the vm). However if I substitute Spark for one of the smack apps and leave the other in place, then its calls to nextMessage return just fine when I send a message from Spark. The two xml messages look the same, so how come one works and one does not? BTW this happens with both a local wildfire server and against ijabber.com, so I suspect it’'s not a server issue.

Of course I should just walk away from nextMessage and use a packetListener on the xmppconnection (though NOT a listener on the Chat object since that also blocks!), but I’'d like to understand fully exactly WHY Chat.nextMessage may not return

My suspicion is that it may be a thread related issue. Could you post the code that you are using to send messages as well as the XML traffic going back and forth?