Creating the Socket Class to Send and Receive Messages


The SocketClass.java file opens the socket to establish a connection with the Jabber server, to send and receive messages between an end user and the Jabber server. Listing 2-4 shows the contents of the SocketClass.java file:

Listing 2-4: The SocketClass.java File

start example
 /*Imports required util classes*/ import java.util.*; /*Imports required io classes*/ import java.io.*; /*Imports required net classes*/ import java.net.*; /*Imports required swing classes*/ import javax.swing.*; /* class SocketClass-This class is used to open a socket and sends and receives Jabber messages. Constructor: SocketClass-This constructor creates GUI. sendername: This method is called to substracte sender name from input message. checkForError: This method is called to check whether the input string contains an error message or not. sendXMLToJabber: This method is called to send XML message to Jabber server. closeConnection: This method is called to close client socket. run: This method is called to listen server response sended by jabber server. */ class SocketClass implements Runnable {    /*Declares objects of Vector class.*/    Vector tagvactor;    /*Declares objects of PrintWriter class.*/    PrintWriter out = null;    /*     Declares objects of BufferedReader class.    */    BufferedReader in = null;    Socket clientsocket;    Thread inputmessagethread;    /*Declares objects of String class.*/    String errortype;    String resource="Home";    String username="";    String password="";    String sendername="";    String  recevername="";    String registrationstring;    String servermessage="";    String ipaddress="";    String endtagstr="";    /*Declares object of UserLogin class.*/    UserLogin userloginhandler;    /*Declares object of JabberClient class.*/    JabberClient jabberclient;    int portno;    int wait=1000;    public boolean isConnected=false;    public SocketClass(JabberClient jc)    {       jabberclient=jc;    }    /*    isConnected: This method is called retrieve socket state.    Parameter: N/A    Return Value: boolean    */    public boolean isConnected()    {       return isConnected;    }    /*    setUserLoginHandler: This method is called to set handler of the object of UserLogin class.    Parameter: userlogin-Object of UserLogin  class.    Return Value: N/A    */    public void setUserLoginHandler(UserLogin userlogin)    {       userloginhandler=userlogin;    }    /*    socketoOpenClass: This method is called to open a socket and gets input and output streams.    Parameter: ipaddress-Object of String class, portno, wait    Return Value: N/A    */    public void socketoOpenClass(String ipaddress, int portno, int wait)    {       this.ipaddress=ipaddress;       this.portno=portno;       this.wait=wait;       openPort(ipaddress,portno,wait);       if (clientsocket!=null)       {          isConnected=true;       }       else       { JOptionPane.showMessageDialog(null, "Server not found.", "Error", JOptionPane.PLAIN_MESSAGE);       return;       }       try       {          out = new PrintWriter(clientsocket.getOutputStream(), true);          in = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));       }       catch(Exception e)       {          e.printStackTrace();       }       inputmessagethread=new Thread(this);                inputmessagethread.start();    }    /*    sendSessionStartMessage: This method is called to create a XML message string.    Parameter: N/A    Return Value: String    */    public String sendSessionStartMessage()    {       String sessionStratString;       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\">";       return sessionStratString;    }    /*    sendAuthorized:  This method is called to create a XML message string.    Parameter: ipaddress - Object of String class, portno, wait    Return Value: N/A    */    public String sendAuthorized()    {       String authentication;       authentication="<iq type=\"set\" id=\"1\">";       authentication=authentication+" <query xmlns=\"jabber:iq:auth\">";       authentication=authentication+" <username>"+username+"</username>";       authentication=authentication+" <password>"+password+"</password>";       authentication=authentication+" <resource>"+resource+"</resource> ";       authentication=authentication+" </query> ";       authentication=authentication+"</iq>";                         return authentication;    }    /*    sendRegistration:  This method is called to create a XML message string.    Parameter: ipaddress - Object of String class, portno, wait    Return Value: N/A    */    public String sendRegistration()    {       String registrationstr="";       registrationstr="<iq type='set' to='"+username+".localhost' id='1'>";       registrationstr=registrationstr+"<query xmlns='jabber:iq:register'>";       registrationstr=registrationstr+"<username>"+username+"</username>";       registrationstr=registrationstr+"<password>"+password+"</password>";       registrationstr=registrationstr+"</query></iq>";       return registrationstr;    }    /*    setUserNameAndPassword:  This method is called to set user name, password and servername    Parameter: username - Object of String class, password - Object of  String class, servername -    Object of  String class.    Return Value: N/A    */    public void setUserNameAndPassword(String username, String password, String servername)    {       this.username=username;       this.password=password;       this.ipaddress=servername;    }    /*    openPort:  This method is called to open a client socket.    Parameter: ipaddress - Object of String class, portno, timeinsec    Return Value: N/A    */    private void openPort(String ipaddress,int portno,int timeinsec)    {       String host;       if (ipaddress.trim()=="")       {          System.out.println("No IP Address Specified.");       }       else       {          SocketOpener sc=new SocketOpener(); Clientsocket=sc.openSocket(ipaddress,portno,timeinsec);       }    }    /*    run:  This method is called to listen server   response sended by jabber server    Parameter: N/A    Return Value: N/A    */    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;                ervermessage=servermessage+(char)i;                if ((char)i=='<')                {                   starttag=true;                   starttagsing=1;                   stagentity="";                }                else                {                   if ((char)i=='/' && starttag==true)                   {                      if (starttagsing==1)                      {                         starttag=false;                         endtag=true;                         startwritting=false;                         vactorindex=vactorindex-1;                         if (vactorindex>=0) agvactor.removeElementAt(vactorindex);                      }                      tagentity=tagentity+(char)i;                   }                   else                   {                   starttagsing=0;                   if((char)i=='>')                {                   jabberclient.setServerResponse(servermessage);                   servermessage="";                   if (endtag&&endtagstr.equals("stream:stream"))                   {                      jabberclient.setStatusLabel("Logged Off");                      jabberclient.setStatus("notconnected");                      jabberclient.disableAndEnableMenuItems(true);                   }                   if (endtag)                   {                      endtagstr="";                      endtag=false;                   }                   if (starttag)                   {                      if (tagentity.endsWith("/"))                      { tagentity=tagentity.substring(0,tagentity.leng  th()-1);                      }                      sendername(tagentity);                      if (tagentity.equals("remove"))                      {jabberclient.setStatusLabel("Not Connected");                      jabberclient.setStatus(""); jabberclient.disableAndEnableMenuItems(true);                      } errorstring=checkForError(tagentity);                      if (errorstring.equals("unauthorized"))                      {                         jabberclient.setStatus(""); JOptionPane.showMessageDialog(null, "User name or                         password is invalid.", "Error",JOptionPane.PLAIN_MESSAGE);                      }                      if (errorstring.equals("user exists"))                      {                         if (jabberclient.getStatus().equals("waitforreg"))                         {                            jabberclient.setStatus("");                            JOptionPane.showMessageDialog(null,"User ID already exists, Please choose                            other User ID.", "Error", JOptionPane.PLAIN_MESSAGE);                         }                      }                      if (errorstring.equals("User not exists.")&&messagebody.equals(""))                      {                         jabberclient.setStatusLabel(" Room does not exist");                         JOptionPane.showMessageDialog(null,"Room does not                         exist.","Error",JOptionPane.PLAIN_MESSAGE);                      }                   else if (errorstring.equals("User notexists.")&&(!messagebody.equals("")))                   {                      messagebody="";                      JOptionPane.showMessageDialog(null,"User dose not                      exists.","Error",JOptionPane.PLAIN_MESSAGE);                   }                   if (tagentity.equals("feature var='http://jabber.org/protocol/muc'"))                   {                      sendXMLToJabber("<presence from='"+username+"@conference."+ipaddress+"/Home'                      to='"+jabberclient.getRoomName()+"@conference."+ipaddress+"/"+username+"'/>");                   }                   if (tagentity.indexOf("type='result'")!=-1)                   {                      String status=jabberclient.getStatus();                      if (status.equals("waitforauth"))                      {                         jabberclient.setStatusLabel("User authenticated");                         jabberclient.setStatus("auth");                         jabberclient.disableAndEnableMenuItems(false);                      }                      if (status.equals("waitforreg"))                      {jabberclient.setStatusLabel("Registered");                      jabberclient.setStatus("reg");                      }                   }                   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;                   }                   if (endtag)                   {                      endtagstr=endtagstr+(char)i;                   }                }             }          }       }     }     catch(IOException ie)     {     }   }   isConnected=false;   } /* closeConnection: This method is called to close client socket. Parameter: N/A Return Value: N/A */ public void closeConnection() {    try    {       out.close();       in.close();       clientsocket.close();    }    catch (IOException e)     {       System.out.println(e);    }    isConnected=false; } /* sendXMLToJabber: This method is called to send XML message to 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();    } } /* checkForError:  This method is called to check whether the input string contains an error message or not. Parameter: tagentity - Object of String class. Return Value: String */ public String checkForError(String tagentity) {    String error="";    String codeid="";    if ( tagentity.equals("error code='403' type='auth'"))    {       return "unauthorized";    }    if (tagentity.equals("error  code='404' type='cancel'"))    {       return "User not exists.";    }    if ((tagentity.indexOf("code='401'")>1)||(tagentity.indexOf("code=\"401\"")>1))    {       return "unauthorized";    }    if (tagentity.equals("error code='409' type='cancel'"))    {       return "user exists";    }    if ((tagentity.indexOf("code='409'")>1)||(tagentity.indexOf("code=\"409\"")>1))    {       return "user exists";    }    return error; } /* sendername: This method is called to  substracte sender name from input message. Parameter: tagentity - Object of String class. Return Value: N/A */ public void sendername(String tagentity) {    if (tagentity.startsWith("message"))    {       sendername="";       recevername=""; if(tagentity.indexOf("from=")>0&&tagentity.indxOf("to=")>0)       {          sendername=tagentity.substring(tagentity.indexOf("from=")+6,tagentity.indexOf("to=")-2);       }       if (tagentity.indexOf("to=")>0&&tagentity.indexOf("type=")>0)       { recevername=tagentity.substring(tagentity.indexOf("to=")+4,tagentity.indexOf("type=")-2);       }     }   } } class SocketOpener {    private Socket socket;    public Socket openSocket(String hostip,int portnumber, int timeinsec)    {       try       {          socket=new Socket(hostip,portnumber);       }       catch(IOException ie)       {          System.out.println("IE:::::::::: " +ie);       }       return getSocket();    }    public SocketOpener()    {    }    public Socket getSocket()    {       return socket;    } }; 
end example

Download this listing.

In the above code, the constructor of the SocketClass class takes the object of the JabberClient class to invoke the methods of the JabberClient class.

The methods defined in Listing 2-4 are:

  • sendername(): Retrieves the sender’s name from the input message received from the Jabber server.

  • checkForError(): Checks whether or not the input string contains an error message.

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

  • closeConnection(): Closes the client socket from the Jabber server.

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

  • isConnected(): Determines whether or not a client socket is connected to the Jabber server.

  • setUserLoginHandler(): Sets the handler of the object of the UserLogin class.

  • socketoOpenClass(): Calls the openPort() method to open a client socket and gets input and output streams to send and receive messages.

  • sendSessionStartMessage(): Creates an XML message string to initialize the session of an end user.

  • sendAuthorized(): Creates an XML message string to authenticate the end users.

  • sendRegistration(): Creates an XML message string to sign up for a new account with the Jabber server.

  • setUserNameAndPassword(): Sets the user name, password, and Jabber server name.

  • openPort(): Opens a client socket by using the IP address and port number of the Jabber server.




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