Creating the Socket Class to Send and Receive Messages


The SocketClass.java file opens the socket with the Jabber server to send and receive messages between end users. Listing 6-4 shows the contents of the SocketClass.java file:

Listing 6-4: The SocketClass.java File

start example
 /*Imports required java.util classes*/ import java.util.*; /*Imports required java.io classes*/ import java.io.*; /*Imports required java.net classes*/ import java.net.*; /*Imports required javax.swing classes*/ import javax.swing.*; /* class SocketClass - This class is used for reading the input messages and writing output messages.  Constructor: SocketClass - This constructor calls a method of SocketOpener class to open a client socket. Methods: */ class SocketClass implements Runnable {    public boolean isConnected;    /*Declare the object of the Vector class.*/    public Vector tagvactor;    /*    Declare the objects of the PrintWriter class.    */    PrintWriter out = null;    /*Declare the objects of the BufferedReader class.*/    BufferedReader in = null;    /*Declare the objects of the String class.*/    String ipaddress="";    String errortype;    String resource="Airline";    String username;    String password;    /*Declare the objects of the Socket class.*/    Socket clientsocket;    /*Declare the objects of the Thread class.*/    Thread inputmessagethread;    /*    Declare the objects of the ReservationStatus class.    */    ReservationStatus reservation;    int portno=5222;    int wait=1000;    public SocketClass(String ipaddress, int portno, int wait, ReservationStatus reservation)    {       this.ipaddress=ipaddress;       this.portno=portno;       this.wait=wait;       this.reservation=reservation;       /*Call openPort() method.*/       openPort(ipaddress,portno,wait);       if (clientsocket!=null)       {       isConnected=true;       }       try       {       /*       Initializes the object of PrintWriter class.       */       out = new PrintWriter(clientsocket.getOutputStream(), true);       /*       Initializes the object of PrintWriter class.       */       in = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));       }       catch(Exception e)       {       e.printStackTrace();       }       /*       Declare the objects of the String class.       */       String sessionStratString;       String registrationstring;       String authentication;       username=reservation.getUserName();       sessionStratString="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";       sessionStratString=sessionStratString+" <stream:stream";       sessionStratString=sessionStratString+" to= \""+ipaddress +"\"";       sessionStratString=sessionStratString+"  xmlns=\"jabber:client\"";       sessionStratString=sessionStratString+" xmlns:stream=\"http://etherx.jabber.org/streams\">";       sendXMLToJabber(sessionStratString);       registrationstring="<iq type=\"set\" id=\"1301\">";       registrationstring=registrationstring+"<query xmlns=\"jabber:iq:register\">";       registrationstring=registrationstring+"<username>"+username+"</username>";       registrationstring=registrationstring+"<password>"+username+"</password>";       registrationstring=registrationstring+"</query></iq>";       sendXMLToJabber(registrationstring);       authentication="<iq type=\"set\" id=\"1301\">";       authentication=authentication+" <query xmlns=\"jabber:iq:auth\">";       authentication=authentication+" <username>"+username+"</username>";       authentication=authentication+" <password>"+username+"</password>";       authentication=authentication+" <resource>"+resource+"</resource> ";       authentication=authentication+" </query> ";       authentication=authentication+"</iq>";       sendXMLToJabber(authentication);       /*       Initializes the object of Thread class.       */       inputmessagethread=new Thread(this);       /*       Calls start() method of the object of Thread class.       */       inputmessagethread.start();    }    /*    openPort: This method creates an object of SocketOpener class and class openSocket method of this    class.    Parameter: ipaddress - Object of String class,portno - int, timeinsec - int     Return Value: N/A    */    private void openPort(String ipaddress,int portno,int timeinsec)    {       /*       Declare the objects of the String class.       */       String host;       if (ipaddress.trim()=="")       {          System.out.println("No IP Address Specified.");       }       else       {          /*          Declare and initializes the objects of the SocketOpener class.          */          SocketOpener socketopener=new SocketOpener();          /*          Calls openSocket Method() of SocketOpener          */          clientsocket=socketopener.openSocket(ipaddress,portno,timeinsec);       }    }    public void run()    {    int i=0;    String errororwarning="";    String errorstring="";    String inputstring="";    boolean starttag=false;    boolean endtag=false;    boolean startwritting=false;    String messagebody="";    String tagentity="";    Vector tagvactor;    tagvactor=new Vector();    int vactorindex=0;    int starttagsing=0;    while (true)    {    try    {    i=in.read();    if (i==-1)    {       break;    }    else    {    inputstring=inputstring+(char)i;    if ((char)i=='<')    {       starttag=true;       starttagsing=1;       tagentity="";    }    else    {    if ((char)i=='/' && starttag==true )    {       if (starttagsing==1)       {          starttag=false;          endtag=true;          reservation.setTableContent(messagebody);          startwritting=false;          messagebody="";          vactorindex=vactorindex-1;          if (vactorindex>=0)          tagvactor.removeElementAt(vactorindex);       }    }    else    {    starttagsing=0;    if((char)i=='>')    {    if (starttag)    {       sendername(tagentity);       errorstring=checkForError(tagentity);       if (!errorstring.equals(""))       {       if (errortype=="major")       {          errororwarning="Error";          JOptionPane.showMessageDialog(null,errorstring,errororwarning,JOptionPane.PLAIN_MESSAGE);       }       else       {          errororwarning="Warning";          JOptionPane.showMessageDialog(null,errorstring,errororwarning,JOptionPane.PLAIN_MESSAGE);       }    }    startwritting=true;    tagvactor.insertElementAt(tagentity,vactorindex);    vactorindex=vactorindex+1;    starttag=false;    } } else {    if (startwritting==true&&tagentity.trim().equals("body"))    {       messagebody=messagebody+(char)i;    }    if (starttag)    {       tagentity=tagentity+(char)i;    } } } } } } catch(IOException ie) { } } isConnected=false; } /* sendXMLToJabber: This method sends XML message string for the jabber server. Parameter: outputmessage - object of String class Return Value: N/A */ public void sendXMLToJabber(String outputmessage) { String[] tokenizerstring=outputmessage.split("\n"); for (int i=0;i<tokenizerstring.length;i++ ) {    try    {       out.println(tokenizerstring[i]);       out.flush();    }    catch(Exception e)    {       System.out.println("error");       return;    }    out.flush();    } } /* getErrorString: This method checks input string for error code. Parameter: codeid - object of String class Return Value: String */ public String getErrorString(String codeid) {    if (codeid=="'401'")    {       errortype="minor";       return "You have sent malformed syntax, which can not be understood by server.";    }    if (codeid=="'404'")    {       errortype="major";       return "No User exist with this user id.";    }    if (codeid=="'405'")    {       errortype="minor";       return "You have no right to send this command.";    }    if (codeid=="'409'")    {       errortype="major";       return "A user with this jabber id is already exist. Please choose another user id.";    }    return ""; } /* checkForError: This method subtracts input string, retrieves errorcode and calls getErrorString() Parameter: tagentity - object of String class Return Value: String */ public String checkForError(String tagentity) {    String error="";    String codeid="";    if (tagentity.startsWith("error"))    {       if (tagentity.indexOf("code=")>0)       {          codeid=tagentity.substring(tagentity.indexOf("code=")+6,tagentity.indexOf("type="));          error=getErrorString(codeid.trim());       }    }    return error; } /* sendername: This method extracts sender name from input message. Parameter: tagentity - object of String class Return Value: N/A */ public void sendername(String tagentity) {    String sendername="";    if (tagentity.startsWith("message"))    {       if (tagentity.indexOf("from=")>0&&tagentity.indexOf("from=")+6,tagentity.indexOf("BlueLine" border="0" cellspacing="0" cellpadding="0" width="100%">  end example   

Download this listing.

In the above code, the constructor of the SocketClass class takes an object of the ReservationStatus class, ipaddress, portno, and wait as input parameters. The object of the ReservationStatus class allows an end user to invoke the methods of the ReservationStatus class. The ipaddress string retrieves the ip address of the Jabber server to connect. The portno int retrieves the port number of the Jabber server to open the socket. The wait int retrieves the initial time to wait before connecting to the Jabber server.

The methods defined in Listing 6-4 are:

  • openPort(): Creates an object of the SocketOpener class and calls the openSocket() method by using the object of the SocketOpener class to open a socket between the Airline Reservation application and the Jabber server.

  • sendXMLToJabber(): Sends an XML message string to the Jabber server.

  • checkForError(): Checks for errors in the information specified by end users and calls the getErrorString() method. The checkForError() method passes the error code to the getErrorString() method as an input parameter.

  • getErrorString(): Shows an error message to end users based on the error code passed as an input parameter.

  • sendername(): Retrieves the name of the sender from the input message and checks the identity of the sender.

  • run(): Listens for the response sent by the Jabber server.

  • OpenSocket(): Initializes the object of the SocketOpener class.

  • getSocket(): Returns an object of the Socket class.




Developing Applications Using Jabber
Developing Applications Using Jabber
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 68

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net