Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Client Server Email Problem

Options
  • 04-11-2008 12:49am
    #1
    Registered Users Posts: 18,272 ✭✭✭✭


    Hi,

    I'm trying to make a VERY simple email client and server in java and I've hit a bit of a problem.

    Here is the code in the client that sends the username to the server
    [b]Client[/b] 
    
    
    if ((message.trim()).equals (endMessage))
                {
                   done = true;
                   helper.done( );
                }
                else {
                	System.out.println("Enter your username");
                	username= br.readLine();
                   if(helper.connect(username) == true)
                   {
                	   loggedin = true;
                   }
    
    [b]Client Helper[/b]
    
    
    public boolean connect(String newUser)throws SocketException,
       IOException 
       {
    	   String response;
    	   System.out.println("HELLO");
    	   mySocket.sendMessage(newUser);
    	   response = mySocket.receiveMessage();
    	   System.out.println("hghg: " + response);
    	   System.out.println("HELLO2");
    	   if(response.equals("logged in"))
    	      {
    	    	  return true;
    	      }
    	   else
    	      return false;
       }
    

    This code asks the user to enter a username on the command line

    here is the server code
    [b]Server[/b] 
    
    
    public static boolean login(String username)
       {	boolean outcome = false;
    	   for(User u : users)
    	   {
    		   
    		   if(u.equals(username))
    		   {
    			   outcome = true;
    		   }
    		   else{
    			   outcome = false;
    		   }}
    	   return outcome;
    	   
    			   
       }
    

    [b]Server Helper[/b]
    
    if ((message.trim()).equals (endMessage)){
    	                //Session over; close the data socket.
    	/**/            System.out.println("Session over.");
    	                myDataSocket.close( );
    	                done = true;
    	             } //end if
    	             
    	             else if(message.equals("login")) 
    	             {
    	                username = myDataSocket.receiveMessage();
    	                
    	                System.out.println(username);
    	                
    	                login(username);
    	             
    	                if(EchoServer3.login(username))
    	                {
    	                	myDataSocket.sendMessage("logged in");
    	                }
    	                else
    	                {
    	                	myDataSocket.sendMessage("login failed");
    	                }
    

    When I input a username on the command line, it gets as far as the first HELLO print statement but then nothing appears afeter that, I was wondering if anyone can spot an error anywhere in the code

    Thanks in advance


Comments

  • Registered Users Posts: 1,996 ✭✭✭lynchie


    Well either your sendMessage call is not returning or your receiveMessage method is blocking waiting on a reply. Too hard to tell without seeing the code in its entirety.


  • Registered Users Posts: 18,272 ✭✭✭✭Atomic Pineapple


    lynchie wrote: »
    Well either your sendMessage call is not returning or your receiveMessage method is blocking waiting on a reply. Too hard to tell without seeing the code in its entirety.

    yep, I figured it was a missing recieve or send, cant seem to work it out at all, heres the entire code if anyone wants to glance over it, it doesnt really matter

    Client
    package Client;
    import java.io.*;
    import java.util.Vector;
    
    import object.EmailObject;
    
    
    public class EchoClient2 {
       static final String endMessage = ".";
       public static void main(String[] args) {
          InputStreamReader is = new InputStreamReader(System.in);
          BufferedReader br = new BufferedReader(is);
          
          String response = "";
          String username = "";
          
          
          try {
             System.out.println("Welcome to the Echo client.\n" +
                "What is the name of the server host?");
             String hostName = br.readLine();
             
             
             if (hostName.length() == 0) // if user did not enter a name
                hostName = "localhost";  //   use the default host name
             System.out.println("What is the port number of the server host?");
             String portNum = br.readLine();
             
             
             if (portNum.length() == 0)
                portNum = "1013";          // default port number
             EchoClientHelper2 helper = 
                new EchoClientHelper2(hostName, portNum);
             boolean done = false;
             boolean connected = false;
             boolean loggedin = false;
             String message, echo, option;
             
             
             if (!connected) {
                System.out.println("Enter login, or a single period to quit.");
                message = br.readLine( );
                if ((message.trim()).equals (endMessage))
                {
                   done = true;
                   helper.done( );
                }
                else {
                	System.out.println("Enter your username");
                	username= br.readLine();
                	System.out.println(username);
                	System.out.println(helper.connect((username)));
                	System.out.println("here");
                   if(helper.connect(username))
                   {
                	   loggedin = true;
                	   connected = true;
                   }
                   else if(connected)
                {
                	System.out.println("Enter 'send', 'read' or '.'");
                	message = br.readLine();
                	if ((message.trim()).equals (endMessage))
                    {
                       done = true;
                       helper.done( );
                    }
                	else if(message.equals("send"))
                	{
                		System.out.println("Enter the reciever");
                		String reciver = br.readLine();
                		
                		
                		System.out.println("Enter the message");
                		String body = br.readLine();
                		response = helper.sendMessage(reciver, username, body);
                		System.out.println(response);
                		
                	}
                	else if(message.equals("read")) {
                		Vector<EmailObject> r = helper.getUnreadMsgs(username);
                		
                		for(EmailObject v : r) {
                			System.out.println(v.getSender());
                			System.out.println(v.getReciever());
                			System.out.println(v.getMessage());
                		}
                	}
                			
                		
                			
                }
                
                
             
             } 
          }} // end try  
          catch (Exception ex) {
             ex.printStackTrace( );
          } //end catch
       } //end main
       
    } // end class
    



    Client Helper
    package Client;
    import java.net.*;
    import java.util.Vector;
    import java.io.*;
    
    import object.EmailObject;
    
    
    
    
    public class EchoClientHelper2 {
    
       static final String endMessage = ".";
       private MyStreamSocket mySocket;
       private InetAddress serverHost;
       private int serverPort;
       
       private static BufferedReader in, userEntry;
       private static PrintWriter out;
       private static String name;
       
    
       EchoClientHelper2(String hostName,
                         String portNum) throws SocketException,
                         UnknownHostException, IOException {
    	    userEntry = new BufferedReader(new InputStreamReader(System.in));
    	    in = new BufferedReader(new InputStreamReader(System.in));
      	    this.serverHost = InetAddress.getByName(hostName);
      		this.serverPort = Integer.parseInt(portNum);
          
       	this.mySocket = new MyStreamSocket(this.serverHost,
             this.serverPort); 
    /**/  System.out.println("Connection request made");
       } // end constructor
    	
       public String getEcho( String message) throws SocketException,
          IOException{     
          String echo = "";    
          mySocket.sendMessage( message);
    	   
          echo = mySocket.receiveMessage();
          return echo;
       } 
    
       public void done( ) throws SocketException,
                                  IOException{
          mySocket.sendMessage(endMessage);
          mySocket.close( );
       } // end done 
       
       public boolean connect(String newUser)throws SocketException,
       IOException 
       {
    	   String response = "";
    	   mySocket.sendMessage("login");
    	   System.out.println("HELLO");
    	   System.out.println("hghg: " + response);
    	   System.out.println("hghg: " + newUser);
    	   mySocket.sendMessage(newUser);
    	   System.out.println("hghg324234: " + newUser);
    	   response = mySocket.receiveMessage();
    	   System.out.println("hghg: " + response);
    	   System.out.println("HELLO2");
    	   if(response.equals("logged in"))
    	      {
    	    	  return true;
    	      }
    	   else
    	      return false;
       }
       
       public String sendMessage(String reciever, String sender, String text) throws IOException
       {
    	   System.out.println("send message");
    	   mySocket.sendMessage("sendMessage");
    	   
    	   mySocket.sendMessage(reciever);
    	   mySocket.sendMessage(sender);
    	   mySocket.sendMessage(text);
    	   
    	   
    	   return mySocket.receiveMessage();
       }
    
       public Vector getUnreadMsgs(String user) throws IOException {
    	   
    	   
    	   mySocket.sendMessage("getUnreadMsgs");
    	   
    	   Vector<EmailObject> emails = new Vector<EmailObject>();
    	   EmailObject m = new EmailObject();
    	   int loops = Integer.parseInt(mySocket.receiveMessage());
    	   
    	   for (int i = 0; i < loops; i++){
    		   String to = mySocket.receiveMessage();
    		   String from = mySocket.receiveMessage();
    		   String bodytext = mySocket.receiveMessage();
    		   
    		   m.setReciever(to); 
    		   m.setSender(from);
    		   m.setMessage(bodytext);
    		   
    		   emails.add(m);
    	   }
    	   
    	   ;
    	   return emails;
       }
    
       
    } //end class
    


    Server
    package Server;
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    
    import object.EmailObject;
    import object.Inbox;
    import object.User;
    
    
    
    
    
    import Client.MyStreamSocket;
    
    
    
    public class EchoServer3 
    {
    	static User u = new User("donal");
    	
    	private static Vector<Inbox> inboxes = new Vector<Inbox>();
    	private static Vector<User> users = new Vector<User>();
    	
       public static void main(String[] args) 
       {
    	   
    	   Inbox draffod = new Inbox("draffod");
    	   Inbox aocon = new Inbox("aocon");
    	   EmailObject m = new EmailObject("draffod", "aocon");
    	   
    	   aocon.addMessage(m);
    	   
    	   inboxes.add(aocon);
    	   inboxes.add(draffod);
    	   users.add(u);
    	   
    	   
    	   
          int serverPort = 1013;    
          String message;
    
           
          try {
             
       	   ServerSocket myConnectionSocket = 
                new ServerSocket(serverPort); 
         System.out.println("Message server ready.");  
             while (true) {  // forever loop
                     System.out.println("Waiting for a connection.");
                MyStreamSocket myDataSocket = new MyStreamSocket
                    (myConnectionSocket.accept( ));
            System.out.println("connection accepted");
             message = myDataSocket.receiveMessage();
             System.out.println(message);
             if(message == "login"){
            	 
            	 System.out.println("login Recieved");
            	 
             }
                
                Thread theThread = 
                   new Thread(new EchoServerThread(myDataSocket));
                theThread.start();
                
                // and go on to the next client
                } //end while forever
           } // end try
    	    catch (Exception ex) {
              ex.printStackTrace( );
    	    } // end catch
       } //end main
       
       public static boolean login(String username)
       {	boolean outcome = false;
    	   for(User u : users)
    	   {
    		   
    		   if(u.equals(username))
    		   {
    			   outcome = true;
    		   }
    		   else{
    			   outcome = false;
    		   }}
    	   return outcome;
    	   
    			   
       }
      
       public static Boolean addToInbox(EmailObject m)
       {
    	   System.out.println("In server add to inbox");
    	   String reciever =  m.getReciever();
    	  for(Inbox i : inboxes)
    	  {
    		  if(i.equals(reciever))
    		  {
    			  
    			  return true;
    		  }
    			   
    	  }
    	  return false;
       }
       
       public static Vector<EmailObject> getMessages(String userName)
       {
    	   Vector<EmailObject> unread = new Vector<EmailObject>();
    	   int c = 0;
    	   for(Inbox i : inboxes)
    	   {
    			  if(i.equals(userName))
    			  {
    				  
    				  
    				 break;
    			  }
    			  else
    			  {
    				  c++;
    			  }
    	   }
       
    	   
    	   Inbox box = inboxes.get(c);
    	   
    	   Vector<EmailObject> messages = box.getMessages();
    	   
    	   int o = 0;
    	   for(EmailObject m : messages)
    	   {
    		   
    			   unread.add(m);
    		   
    			o++;
    	   }
    	   System.out.println("unread size: " + unread.size());
    	   return unread;
    	   
    	   
       }
       
       
    } // end class
    

    Server Helper
    package Server;
    
    import java.util.ArrayList;
    import java.util.Vector;
    
    import object.EmailObject;
    import object.Inbox;
    import object.User;
    
    
    import Client.MyStreamSocket;
    
    class EchoServerThread implements Runnable {
    	   String username;
    		static final String endMessage = ".";
    	   MyStreamSocket myDataSocket;
    	   
    	   EchoServerThread(MyStreamSocket myDataSocket) {
    	      this.myDataSocket = myDataSocket;
    	   }
    	 
    	   public void run( ) {
    	      boolean done = false;
    	      String message;
    	      try {
    	             message = myDataSocket.receiveMessage( );
    				
    	             if ((message.trim()).equals (endMessage)){
    	             
                        System.out.println("Session over.");
    	                myDataSocket.close( );
    	                done = true;
    	             } 
    	             
    	             else if(message.equals("login")) 
    	             {
    	            	 System.out.println("gets to here.");
    	                username = myDataSocket.receiveMessage();
    	                System.out.println("gets to here two.");
    	                System.out.println(username);
    	                
    	                login(username);
    	             
    	                if(EchoServer3.login(username))
    	                {
    	                	myDataSocket.sendMessage("logged in");
    	                }
    	                else
    	                {
    	                	myDataSocket.sendMessage("login failed");
    	                }
    	                	
    	               
    	             }
    	             
    	             message = myDataSocket.receiveMessage( );
    	             if(message.equals("sendMessage"))
    	             {
    	            	System.out.println("In thred send message");
    	            	String sender = myDataSocket.receiveMessage();
    	            	String body = myDataSocket.receiveMessage();
    	            	
    	            	
    	                
    	               
    	            	
    	            	EmailObject m = new EmailObject( sender, body);
    	            	if(EchoServer3.addToInbox(m))
    	            	{
    	            		myDataSocket.sendMessage("MessageSent");
    	            		
    	            	}
    	            	else
    	            	{
    	            		myDataSocket.sendMessage("MessageFailed");
    	            	}
    	             }
    	             
    	             //message = myDataSocket.receiveMessage( );
    	             if(message.equals("getUnreadMsgs"))
    	             {
    	            	 Vector v = EchoServer3.getMessages(username);
    	            	 EmailObject mm = new EmailObject();
    	            	 
    	            	 String loops = Integer.toString(v.size());
    	            	 myDataSocket.sendMessage(loops);
    	            	 
    	            	 for (int i = 0; i < v.size(); i++) {
    	            		 mm = (EmailObject) v.get(i);
    	            		 
    	            		 myDataSocket.sendMessage("From: " + mm.getReciever());
    	            		 myDataSocket.sendMessage("Body: " + mm.getMessage());
    	            	 }
    	            	 
    	             }
    	          
    	        }// end try
    	        catch (Exception ex) {
    	           System.out.println("Exception caught in thread: " + ex);
    	        } // end catch
    	   } //end run
    
    		public boolean login(String username)
    		{
    			return EchoServer3.login(username);
    		}
    			
    	} //end class 
    



    I'll post it up if i get it myself


  • Registered Users Posts: 1,996 ✭✭✭lynchie


    Dont see the implementation of MyStreamSocket anywhere? I assume its based on standard java Scokets, so I guess you are using standard IO streams to read write from the sockets? I assume you are flushing the buffers after writing data to them?


  • Registered Users Posts: 18,272 ✭✭✭✭Atomic Pineapple


    lynchie wrote: »
    Dont see the implementation of MyStreamSocket anywhere? I assume its based on standard java Scokets, so I guess you are using standard IO streams to read write from the sockets? I assume you are flushing the buffers after writing data to them?

    sorry i left it out to keep the post a bit shorter, yeh using standard streams

    here is the code
    import java.net.*;
    import java.io.*;
    
    public class MyStreamSocket extends Socket {
       private Socket  socket;
       private BufferedReader input;
       private PrintWriter output;
    
       private InetAddress ipaddress;
    
       MyStreamSocket(InetAddress acceptorHost,
                      int acceptorPort ) throws SocketException,
                                       IOException{
          socket = new Socket(acceptorHost, acceptorPort );
          setStreams( );
          setLocationInfo();
    
       }
    
       public MyStreamSocket(Socket socket)  throws IOException {
          this.socket = socket;
          setStreams( );
          setLocationInfo();
       }
    
       private void setStreams( ) throws IOException{
          // get an input stream for reading from the data socket
          InputStream inStream = socket.getInputStream();
          input =
             new BufferedReader(new InputStreamReader(inStream));
          OutputStream outStream = socket.getOutputStream();
          // create a PrinterWriter object for character-mode output
          output =
             new PrintWriter(new OutputStreamWriter(outStream));
       }
    
       private void setLocationInfo() throws IOException
       {
    	   ipaddress = socket.getInetAddress();
       }
    
       public void sendMessage(String message)
       		          throws IOException {
          output.println(message);
          //The ensuing flush method call is necessary for the data to
          // be written to the socket data stream before the
          // socket is closed.
          output.flush();
       } // end sendMessage
    
       public String receiveMessage( )
    		throws IOException {
          // read a line from the data stream
          String message = input.readLine( );
          return message;
       } //end receiveMessage
    
    
    	
    } //end class
    


  • Registered Users Posts: 1,996 ✭✭✭lynchie


    First off.. if(message == "login") is wrong.. use .equals()
       MyStreamSocket myDataSocket = new MyStreamSocket
                    (myConnectionSocket.accept( ));
            System.out.println("connection accepted");
            [b] message = myDataSocket.receiveMessage();[/b]
             System.out.println(message);
    

    the message contains "login" at this point. You then create the server thread with this socket, and inside it the first thing u do is
     public void run( ) {
    	      boolean done = false;
    	      String message;
    	      try {
    	  [b]           message = myDataSocket.receiveMessage( );[/b]
    

    which blocks and waits for another message without processing the current message.

    I suggest you remove the receiveMessage() call from the EchoServer3 code and it should get past that issue.

    When you do it should go past the hello..
    Welcome to the Echo client.
    What is the name of the server host?
    
    What is the port number of the server host?
    
    Connection request made
    Enter login, or a single period to quit.
    login
    Enter your username
    test
    test
    HELLO
    hghg:
    hghg: test
    hghg324234: test
    hghg: login failed
    HELLO2
    false
    here
    HELLO
    hghg:
    hghg: test
    hghg324234: test
    


  • Advertisement
Advertisement