Creating the Socket Class to Send and Receive Messages


The SocketConnection.java file creates a socket with the Jabber server to send and receive messages between end users. Listing 4-7 shows the contents of the SocketConnection.java file:

Listing 4-7: The SocketConnection.java File

start example
 /*Import required swing classes*/ import javax.swing.*; import javax.swing.JTextPane; import javax.swing.text.*; /*Import required awt classes*/ import java.awt.*; import java.awt.event.*; /*Import required io and net classes*/ import java.io.*; import java.net.*; /*Import required util classes*/ import java.util.*; import java.lang.*; import javax.swing.tree.*; /* class SocketConnection - This class is used to create a GUI to show the group and user. Constructor: SocketConnection-This constructor creates GUI. Methods: openSocket - Used to open the port. socketope - Used to instantiate the socket class. getErrorString-Used to get the error string. sendername-Used to get the sendername. checkForError-Used to check XML error. runinput-Used to read the server output */ public  class  SocketConnection {    /*Declare the integer*/    private int openerport;    /*Declare object of Socket class.*/    static private Socket socket;    /*Declare object of PrintWriter class.*/    static PrintWriter out = null;    /*Declare object of BufferedReader class.*/    static BufferedReader in = null;     /*Declare object of MutableAttributeSet class.*/    static MutableAttributeSet sendernameattrib,nameattribut,informationattrib,welcomenameattrib ;    static Document contentmodel;    /*Declare string variables.*/    private String openerhost;    static String errortype="";    String roomname="";    String firstname="";    String lastname="";    String emailid="";    String resource="Home";    String temproomname="";    String username="";    String password="";    String groupname="";    String nickname="";    String servererror="";    String chattype="";    String contactpersonname="";    String jid="";    String sendername="";    String tagentity="";    /*Declare boolean variables*/    private  static boolean isConnected=false;    boolean waitForResult=false;    boolean rosterflag=false;    boolean waitforreg=false;    boolean waitforauth=false;    boolean waitforgroup=false;    boolean groupnameb=false;    boolean nouserexists=false;    /*Declare object of GroupChat class.*/    GroupChat groupuser;    /*Declare object of GroupList class.*/    GroupList group;    /*Declare object of ChatWindow class.*/    ChatWindow chat;    /*Declare object of GroupTree class.*/    GroupTree dynamic;    /*Declare object of GroupLoginGUI class.*/    GroupLoginGUI logingui;    /*Declare object of nicknamevector class.*/    Vector nicknamevector=new Vector();    /*Declare object of HashMap class.*/    HashMap temphashmap=new HashMap();    /*Declare object of Hashtable class.*/    Hashtable onlineuser=new Hashtable();    /*function to open socket*/    public  SocketConnection openSocket(String hostip,int portnumber,int timeinsec)    {       sendernameattrib=new SimpleAttributeSet();       StyleConstants.setFontFamily(sendernameattrib,"Verdana");       StyleConstants.setForeground(sendernameattrib,Color.black);       welcomenameattrib=new SimpleAttributeSet();       StyleConstants.setFontFamily(welcomenameattrib,"Verdana");       StyleConstants.setForeground(welcomenameattrib,Color.blue);       nameattribut=new SimpleAttributeSet();       StyleConstants.setFontFamily(nameattribut,"Verdana");       StyleConstants.setForeground(nameattribut,Color.red);       informationattrib=new SimpleAttributeSet();       StyleConstants.setFontFamily(informationattrib,"Verdana");       StyleConstants.setItalic(informationattrib,true);       StyleConstants.setForeground(informationattrib,Color.red);       socketope();       try       {          out = new PrintWriter(socket.getOutputStream(), true);          in = new BufferedReader(new InputStreamReader(          socket.getInputStream()));       }       catch(Exception exception)       {          JOptionPane.showMessageDialog(logingui,"Server not found","Server not          found",JOptionPane.ERROR_MESSAGE);       }       return getSocketClass();    }    /*    Used to create instance of socket class    Parameter: N/A    Return Value: N/A    */    public  void socketope()    {       try       {          socket=new Socket(openerhost,openerport);       }       catch(IOException ie)       {       }    }    /* Constructor for class */    public SocketConnection(String host,int port,GroupList group,GroupTree dynamic,    GroupLoginGUI logingui)    {       this.group=group;       this.dynamic=dynamic;       this.logingui=logingui;       socket=null;       openerhost=host;       openerport=port;    }    /* Used to get the reference of socket class*/    public SocketConnection getSocketClass()    {       return this;    }    /*    Function to write a get error     Parameter: codeid-Object of string class.    Return Value: String    */    public static 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 Server exist .";       }       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.";       }       if (codeid=="'403'")          {          errortype="auth";          return "Invalid password";       }       return "";    }    /*    Function used to get the sendername    Parameter: tagentity-Object of string class.    Return Value: N/A.    */    public void sendername(String tagentity)    {       if (tagentity.startsWith("message"))       {          sendername="";          if (tagentity.indexOf("from=")>0&&tagentity.indexOf("to=")>0)          {             sendername=tagentity.substring(tagentity.indexOf("from=")+6,tagentity.indexOf("to=")-2);          }       }    }    /*    Function to check xml error    Parameter: tagentity-Object of string class    Return Value: String    */    public static String checkForError(String tagentity)    {    String error="";    String codeid="";    if (tagentity.indexOf("error")>0)    {    if (tagentity.indexOf("from=")>0)    {       codeid=tagentity.substring(tagentity.indexOf("type="));    } } if (tagentity.indexOf("result")>0) { } return error; } /*  Used to set the object of GroupUser Parameter: gc-Object of GroupChat class Return Value: N/A */ public void setGroupuser(GroupChat gc) {    groupuser=gc; } /* Used to read the server output Parameter: N/A Return Value: N/A */ public void runinput() {    int i=0;    String errororwarning="";    String errorstring="";    String inputstring="";    boolean starttag=false;    boolean endtag=false;    boolean startwritting=false;    String messagebody="";    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;                   waitforgroup=false;                   if (!groupname.trim().equals(""))                   {                      String contactperson="";                      contactperson=contactpersonname.substring(1,contactpersonname.length()-1);                      group.addToTree(groupname,jid,contactperson);                   }                   jid="";                   contactpersonname="";                   groupname="";                      if(!messagebody.trim().equals(""))                   {                   if (chattype.equals("chat"))                   {                      group.insertTextInToTextPane(messagebody,sendername);                   }                   else                   {                      String username=logingui.getUserName();                      String name[]=sendername.split("/");                      System.out.println("sender name "+name[1]);                      System.out.println("receiver name "+username);                      if(name[1].equals(username))                      {                         groupuser.writeintotextfield("\n"+name[1]+":"+messagebody, nameattribut);                      }                      else                      {                         groupuser.writeintotextfield("\n"+name[1]+":"+messagebody, sendernameattrib);                      }                   }                }                startwritting=false;                messagebody="";                vactorindex=vactorindex-1;                if (vactorindex>=0)                tagvactor.removeElementAt(vactorindex);             }             if (starttag)             {                stagentity=tagentity+(char)i;             }          }          else          {             starttagsing=0;             if((char)i=='>')             {             if (starttag)             {             sendername(tagentity);             errorstring=checkForError(tagentity);             if((tagentity.indexOf("type='error'")>1) &&             (tagentity.indexOf("id='1301'")>1))             {                String username=logingui.getUserName();                String password=logingui.getPassword();                String servarn=logingui.getServarName();                String registrationstring="<iq type=\"set\" to=\""+username+"@"+servarn+"\"                id=\"1001\">";                registrationstring=registrationstring+"<query xmlns=\"jabber:iq:register\">";                registrationstring=registrationstring+"<username>"+username+"</username>";                registrationstring=registrationstring+"<password>"+password+"</password>";                registrationstring=registrationstring+"<first>"+firstname+"</first>";                registrationstring=registrationstring+"<last>"+lastname+"</last>";                registrationstring=registrationstring+"<email>"+emailid+"</email>";                registrationstring=registrationstring+" </query> ";                registrationstring=registrationstring+"</iq>";                String authentication="<iq type=\"set\" id=\"1301\">";                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>";                sendXMLToJabber(authentication);                sendXMLToJabber(registrationstring);             }             if (errorstring.equals("unauthorized"))             {                sendRegistration();                waitforreg=true;                waitforauth=false;             }             if (tagentity.startsWith("message"))             {                if (tagentity.indexOf("type='groupchat'")>0)             {                chattype="groupchat";             }             else             {                chattype="chat";             }          }          if((tagentity.indexOf("type='result'")>1)&&(waitforreg)&&          (!errorstring.equals("user exist")))          {             sendAuthorized();             waitforauth=true;             waitforreg=false;          }          if((tagentity.indexOf("type='result'")>1)&&(waitforauth))          {             waitforauth=false;          }          if(tagentity.startsWith("presence"))          {             if(tagentity.indexOf("from=")>0&&tagentity.indexOf("to=")>0)             {             nickname=tagentity.substring(tagentity.indexOf("from=")+6,tagentity.indexOf("to=")-1);             String loginuser[]=nickname.split("/");             if (tagentity.indexOf("type='unavailable'")>0||tagentity.indexOf             ("type=\"unavailable\"")>0)             {             }             else             {                Enumeration e=group.hasuser.keys();                while(e.hasMoreElements())                {                   String haselm=(String)e.nextElement();                   String[] userid=nickname.split("/");                   Object nname=group.hasuser.get(haselm);                   String nnamestr=nname.toString();                   if(userid[1].equals(loginuser[1]))                   {                      String loginusertoadd=loginuser[1].substring(0,loginuser[1].length()-1);                      groupuser.addElement(loginusertoadd);                      break;                   }                   if(userid[1].equals(nnamestr+"'"))                   {                      groupuser.addElement(nnamestr);                   }                }             }          }       }       if(tagentity.indexOf("item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'")!=-1)       {          String user=group.getUserName();          String removeuser;          removeuser="<iq type='set' id='1'>";          removeuser=removeuser+"<query xmlns='jabber:iq:roster'>";          removeuser=removeuser+"<item jid='"+user+"@localhost/Home' name='"+user+"'          subscription='remove'/>";          removeuser=removeuser+"</query></iq>";          sendXMLToJabber(removeuser);          String removestring;          JOptionPane.showMessageDialog(group,"No user exists with this user          id.",errororwarning,JOptionPane.PLAIN_MESSAGE);          nouserexists=true;          return;       }       if (rosterflag)       {       if (tagentity.indexOf("item")!=-1 &&       (!nouserexists)&&(tagentity.indexOf("affiliation")==-1))       {          contactpersonname=tagentity.substring(tagentity.indexOf("name")+5,          tagentity.indexOf("jid")).trim();          jid=tagentity.substring(tagentity.indexOf("jid")+4,tagentity.length());          waitforgroup=true;       }       if (tagentity.indexOf("query")!=-1)       {          rosterflag=false;       }    }    if ((tagentity.indexOf("type='result'")>1)&&(!waitforauth)&&(!waitforreg))    {       waitForResult=true;    }    else    {       if (tagentity.indexOf("xmlns='jabber:iq:roster'")>1&&waitForResult)       {          rosterflag=true;          waitForResult=false;       }       waitForResult=false;    }    if (errorstring.equals("user exist")&&waitforreg)    {       JOptionPane.showMessageDialog(null, "A user with this user ID is already exists.Please enter other       user ID.", errororwarning, JOptionPane.PLAIN_MESSAGE);    }    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 (waitforgroup && tagentity.trim().equals("group"))    {       groupname=groupname+(char)i;    }    if(startwritting==true && tagentity.trim().equals("body"))    {       messagebody=messagebody+(char)i;    }    if (starttag)    {       tagentity=tagentity+(char)i;    } } } } } } catch(IOException ie) { } } isConnected=false; } /* Function to set the object of ChatWindow Parameter:chat- Object of ChatWindow class Return Value: N/A */ public void setObjChat(ChatWindow chat) { this.chat=chat; } public void 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>";    sendXMLToJabber(authentication); } /* Used to send the request to jabber server to get the user list Parameter: N/A Return Value: N/A */ public void sendRosterRequest() {    group.clearTree();    String rosterstring="";    rosterstring="<iq type=\"get\" id=\"1\">";    rosterstring=rosterstring+"<query xmlns=\"jabber:iq:roster\"/></iq>";    sendXMLToJabber(rosterstring); } /* Used to create a group by sending a message to jabber server Parameter:group- Object of string class Return Value: N/A */ public void createGroup(String group) {    sendXMLToJabber(group); } public void sendRegistration() {    String registrationstring;    registrationstring="<iq type=\"set\" to=\""+username+".localhost\" id=\"1\">";    registrationstring=registrationstring+"<query xmlns=\"jabber:iq:register\">";    registrationstring=registrationstring+"<username>"+username+"</username>";    registrationstring=registrationstring+"<password>"+password+"</password></    query></iq>"; } /* Used to send the xml messages to jabber server Parameter:outputmessage- Object of string class Return Value: N/A */ public static void sendXMLToJabber(String outputmessage) {    out.println(outputmessage);    out.flush(); } } 
end example

Download this listing.

In the above code, the constructor of the SocketConnection class takes the integer string, the GroupTree class object of the GroupList class, and the GroupLoginGUI class as input parameters. The SocketConnection class allows end users to invoke the methods of the GroupList class, GroupTree class, and GroupLoginGUI class. The host string retrieves the name of the Jabber server and the port integer retrieves the port number of the Jabber server.

The methods defined in Listing 4-7 are:

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

  • Socketope(): Instantiates the Socket class to invoke methods of the Socket class.

  • getErrorString(): Retrieves the error string sent by the Jabber server.

  • 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.

  • runinput(): Reads the response sent by 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