[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Socket Programming and GUI

Posted on 2011-10-16
12
Medium Priority
?
2,023 Views
Last Modified: 2012-06-27
Hi experts,

I'm using JAVA and I'm stuck in how to use my GUI code connected to SQLite database with client server app using socket programming. I have looked at too many books and websites including Sun tutorials but neither have gone in deep. I guess experience plays a role here.
The client and server classes are just examples. They are not related to the work that I'm doing but mainly the mechanism in connecting the sockets btn client and server.

My GUI code is:
package Extra;
import javax.swing.*;
import java.awt.*;
import java.sql.*;
public class SwingLogin {
	public static final  Dimension FRAME_SIZE = new Dimension(1000, 130); 
	JFrame login = new JFrame("User Login");
	JLabel userlbl = new JLabel("Username ");
	JTextField usertxt =  new JTextField(20);
	JLabel passlbl = new JLabel("Password ");
	JPasswordField passtxt =   new JPasswordField(20);
	JButton loginbtn = new JButton("Login");
	JButton clearbtn = new JButton("Clear");
	JLabel txtlbl = new JLabel("");
	
	public void display() {
			 Container contentPane = login.getContentPane();
			 contentPane.setLayout(new FlowLayout());
			 contentPane.setPreferredSize(FRAME_SIZE);
			login.setSize(FRAME_SIZE);
			login.setBackground(Color.LIGHT_GRAY);
			contentPane.add(userlbl);
			contentPane.add(usertxt);
			contentPane.add(passlbl);
			contentPane.add(passtxt);
			contentPane.add(loginbtn);
			contentPane.add(clearbtn);
			contentPane.add(txtlbl);
			login.setVisible(true);
			loginbtn.addActionListener(new java.awt.event.ActionListener() {
	        public  void actionPerformed(java.awt.event.ActionEvent evt) {
	                try {
						loginbtnActionPerformed(evt);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	        });
			
			clearbtn.addActionListener(new java.awt.event.ActionListener() {
		        public  void actionPerformed(java.awt.event.ActionEvent evt) {
		                clearbtnActionPerformed(evt);
		            }
		        });
		}
				
			
		
		
	//method for login button
	@SuppressWarnings("deprecation")
	public  void loginbtnActionPerformed(java.awt.event.ActionEvent evt) throws Exception{
		//txtlbl.setText("Username is " + usertxt.getText() + ", Password is " + passtxt.getText());
		//System.out.println(txtlbl.getText());
		
		Class.forName("org.sqlite.JDBC");
	    Connection conn =
	      DriverManager.getConnection("jdbc:sqlite:/Users/hbargi/MySQLiteDB");
	    Statement stat = conn.createStatement();
	  
	    ResultSet rs = stat.executeQuery("select * from users;");
	    while (rs.next()) {
	      if(rs.getString("username").equals(usertxt.getText()) && rs.getString("password").equals(passtxt.getText()))
	      {
	    	  txtlbl.setText("Login successful!");
	      }
	      else
	      {
	    	  txtlbl.setText("Username & password doesn't match; Please try again!");
	      }
	      //System.out.println("pass = " + rs.getString("password"));
	    }
	    rs.close();
	    conn.close();
	  }



	//method for clear button
	private  void clearbtnActionPerformed(java.awt.event.ActionEvent evt) {
		System.exit(-1);	
	}


public static void main(String args[])
	{
		SwingLogin sw = new SwingLogin();
		sw.display();
	}
}

Open in new window


Server class example:
package Extra;

// TCPEchoServer 
// Received Message From User And send ok to client

import java.net.ServerSocket ;
import java.net.Socket ;
import java.io.IOException ;
import java.io.PrintWriter ;
import java.util.Scanner ;

public class TCPEchoServer
{
   private static final int PORT = 5000 ;
   private static ServerSocket serverSocket ;
   private static Socket socket ;
   
   public static void main (String args[])
   {
      try
      {
         serverSocket = new ServerSocket(PORT);
         System.out.println("********** Server Open Connnection **********");
      }
      catch ( IOException e)
      {
         System.out.println("Unable to Attach To Port !");
         System.exit(1);
      }
      
      while ( true )
         accessClient();
   }
   
   public static void accessClient()
   {
      try
      {
         socket = serverSocket.accept();
         
         Scanner input = new Scanner ( socket.getInputStream() ) ;
         PrintWriter output = new PrintWriter( socket.getOutputStream() , true );
         
         String msgIn , msgOut ;
         
         msgIn = input.nextLine();
         
         while ( ! msgIn.equals("CLOSE") )
         {
            System.out.println("Client > " + msgIn );
            
            msgOut = " OK " ;
            output.println(msgOut);
            
            msgIn = input.nextLine();
         }
         
      }
      catch ( IOException e)
      {   e.printStackTrace();   }
      
      finally
      {
         try
         {
            if ( socket != null )
               socket.close();
            
            System.out.println("Server Close Client Connection !");
         }
         catch ( IOException  e)
         {
            System.out.println("Cannot Disconnect Client !");
            System.exit(1);
         }
      }
   }
}

Open in new window


Client class example:
package Extra;

// TCPEchoClient
// send Message to Server , Received OK Message

import java.net.InetAddress ;
import java.net.UnknownHostException ;
import java.net.Socket ;
import java.io.PrintWriter ;
import java.util.Scanner ;
import java.io.IOException ;

public class TCPEchoClient 
{
   private static final int PORT = 5000 ;
   private static Socket socket ;
   private static InetAddress address ;
   
   public static void main (String args[])
   {
      try
      {
         address = InetAddress.getLocalHost();
      }
      catch (UnknownHostException e)
      {
         System.out.println("Cannot Find IP Number !");
      }
      
      accessServer();
   }
   
   public static void accessServer ()
   {
      try
      {
         socket = new Socket(address,PORT);
         
         Scanner input = new Scanner( socket.getInputStream() );
         PrintWriter output = new PrintWriter( socket.getOutputStream() , true );
         
         String msgIn = "" , msgOut = "";
         
         Scanner uInput = new Scanner( System.in);
         
         while ( ! msgOut.equals("CLOSE") ) 
         {
            System.out.print("Enter Message : " );
            msgOut = uInput.nextLine();
            
            output.println(msgOut);
            
            if ( !msgOut.equals("CLOSE")) 
            {
               msgIn = input.nextLine();   
               System.out.println("Server  > " + msgIn );
            }
         } 
         
      }
      catch ( IOException e)
      {   e.printStackTrace()   ;}
      
      finally
      {
         try
         {
            if ( socket != null )
               socket.close();
            
            System.out.println("Clinet Close Connection !");
         }
         catch ( IOException e)
         {
            System.out.println("Cannot Disconnect Client !");
            System.exit(1);
         }
      }
   }
}

Open in new window


Thanks!
0
Comment
Question by:hmbargi
  • 6
  • 3
  • 3
12 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 36976041
Why don't you just connect directly with TCP/IP to the SQLLite database?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36976049
Sorry, can you elaborate what is the connection between accessing SQLite using JDBC and client-server socket interaction.

Alos please explain what are the specific problems you experience.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36976096

If you just want to know how to do
client-server socket communication
follow this good example form
http://zerioh.tripod.com/ressources/sockets.html

I just put Provider in one class of my IDE
Requester in another
Then made Run configuration with main class of Provider and started it - it writes "Waiting ofr connection"

Then pasted Requester class in anothe file in the same project of my IDE
Created Run configuration wityh main class Requester

then ran it and got outputs in both widows -see below.
Then I stoped server, and saw that client fails to connect.

Alll works fine and seem to be rather simple.
Look at their code and try it, and let me know if you have any questions.

import java.io.*;
import java.net.*;
public class Provider{
	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	Provider(){}
	void run()
	{
		try{
			//1. creating a server socket
			providerSocket = new ServerSocket(2004, 10);
			//2. Wait for connection
			System.out.println("Waiting for connection");
			connection = providerSocket.accept();
			System.out.println("Connection received from " + connection.getInetAddress().getHostName());
			//3. get Input and Output streams
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			sendMessage("Connection successful");
			//4. The two parts communicate via the input and output streams
			do{
				try{
					message = (String)in.readObject();
					System.out.println("client>" + message);
					if (message.equals("bye"))
						sendMessage("bye");
				}
				catch(ClassNotFoundException classnot){
					System.err.println("Data received in unknown format");
				}
			}while(!message.equals("bye"));
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
		finally{
			//4: Closing connection
			try{
				in.close();
				out.close();
				providerSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}
	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	public static void main(String args[])
	{
		Provider server = new Provider();
		while(true){
			server.run();
		}
	}
}

Open in new window



import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Requester{
	Socket requestSocket;
	ObjectOutputStream out;
 	ObjectInputStream in;
 	String message;
	Requester(){}
	void run()
	{
		try{
			//1. creating a socket to connect to the server
			requestSocket = new Socket("localhost", 2004);
			System.out.println("Connected to localhost in port 2004");
			//2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			//3: Communicating with the server
			do{
				try{
					message = (String)in.readObject();
					System.out.println("server>" + message);
					sendMessage("Hi my server");
					message = "bye";
					sendMessage(message);
				}
				catch(ClassNotFoundException classNot){
					System.err.println("data received in unknown format");
				}
			}while(!message.equals("bye"));
		}
		catch(UnknownHostException unknownHost){
			System.err.println("You are trying to connect to an unknown host!");
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
		finally{
			//4: Closing connection
			try{
				in.close();
				out.close();
				requestSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}
	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	public static void main(String args[])
	{
		Requester client = new Requester();
		client.run();
	}
}

Open in new window



Client side output:

Connected to localhost in port 2004
server>Connection successful
client>Hi my server
client>bye

Open in new window


Server side output:

Waiting for connection
Connection received from localhost
server>Connection successful
client>Hi my server
client>bye
server>bye
Waiting for connection
Connection received from localhost
server>Connection successful
client>Hi my server
client>bye
server>bye
Waiting for connection

Open in new window




Client side output when server stopped
java.net.ConnectException: Connection refused: connect
	at java.net.PlainSocketImpl.socketConnect(Native Method)
	at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
	at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
	at java.net.Socket.connect(Socket.java:529)
	at java.net.Socket.connect(Socket.java:478)
	at java.net.Socket.<init>(Socket.java:375)
	at java.net.Socket.<init>(Socket.java:189)
	at Requester.run(Requester.java:17)
	at Requester.main(Requester.java:69)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Exception in thread "main" java.lang.NullPointerException
	at Requester.run(Requester.java:46)
	at Requester.main(Requester.java:69)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:hmbargi
ID: 36976482
I know how to create a client server app but the problem that I'm facing is where to put the database connectivity in my app. Would I put it in the server or the client class. Also, for input and output, would I use Scanner as an input and PrintWriter as an output for all apps including GUIs that deal with database. What I'm looking here is how to integrate my GUI code with client and server class that I provided.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36976517
I am sorry, can you explain what is the relation between database connectivity and server-client sockety programming.
In order to access databse through JDBC you don't need any socket programming - network copnnection is the part which is accomplished by the jdbc driver.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36976667
hmbargi, as a continuation of my first comment, MySql (Lite) is *already* the server part of a client server application. Why do you want to include it in yet another client/server app?
0
 

Author Comment

by:hmbargi
ID: 36976803
I'm sorry if I asked a stupid question. I'm newbie in client server programming. Basically, Im doing Grade Management Project for my class. I need to do the project as a client server app. I developed a simple login page which authenticate users and it works fine. However, I need to do the same login page using sockets but don't know how. All the resources that I have looked are simple which explains the client sends a request and the server responds but never have gone describing how we can use that in GUI apps. Hope you got my point.

Thanks in advance.
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36976819
Oh you just use your interface and together with the client piece - so you take the username and passwrod and send them to the server.
On the server you maintain the table of users/passwords .On the server you compare if your pair fits one of the stored pairs and reply either - success, if it does,
or failure - if it does not.
Just combine your user interface with your client piece (or with the code I supplied).
And on the server side - sya before you start listeneting read the file which would have user/passwiord pairs and when you receive the
pair provided from client compare and return duccess ofr failue back.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36976820
I assume you want the following:

a. client gui sends login request to server
b. server authenticates (or not)
c. client gui takes further action

Is that the idea?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36976888
I just made it working - though based on your GUI and  "my" (the one I posted) server/client code on the back side.
Let me know;if you want, I can post you the code.
I believe you already did a lot of work on this project, so if I post the code for you, it will not be any EE violations about academic assignements.
0
 

Author Comment

by:hmbargi
ID: 36981184
I will be glad if you post the code so I can learn from your wonderful experience.
Thanks for_yan!
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36981270
well, it is of course very quick and dirty but proves that
they communicate.
First you start Provider (it wriites "waiting for connections"

Then you  start SwingLogin.
When you enter aaa/bbb, Login  it will show success in the System output
(see on server(Provider) I encoded user/password: aaa/bbb)

Enter sometyhing else - it will print Failure



package Extra;
import javax.swing.*;
import java.awt.*;
import java.sql.*;
public class SwingLogin {
	public static final  Dimension FRAME_SIZE = new Dimension(1000, 130);
	JFrame login = new JFrame("User Login");
	JLabel userlbl = new JLabel("Username ");
	JTextField usertxt =  new JTextField(20);
	JLabel passlbl = new JLabel("Password ");
	JPasswordField passtxt =   new JPasswordField(20);
	JButton loginbtn = new JButton("Login");
	JButton clearbtn = new JButton("Clear");
	JLabel txtlbl = new JLabel("");
    String result;

    public void setResult(String s){
        result = s;
    }

	public void display() {
			 Container contentPane = login.getContentPane();
			 contentPane.setLayout(new FlowLayout());
			 contentPane.setPreferredSize(FRAME_SIZE);
			login.setSize(FRAME_SIZE);
			login.setBackground(Color.LIGHT_GRAY);
			contentPane.add(userlbl);
			contentPane.add(usertxt);
			contentPane.add(passlbl);
			contentPane.add(passtxt);
			contentPane.add(loginbtn);
			contentPane.add(clearbtn);
			contentPane.add(txtlbl);
			login.setVisible(true);
			loginbtn.addActionListener(new java.awt.event.ActionListener() {
	        public  void actionPerformed(java.awt.event.ActionEvent evt) {
	                try {
						loginbtnActionPerformed(evt);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	        });

			clearbtn.addActionListener(new java.awt.event.ActionListener() {
		        public  void actionPerformed(java.awt.event.ActionEvent evt) {
		                clearbtnActionPerformed(evt);
		            }
		        });
		}




	//method for login button
	@SuppressWarnings("deprecation")
	public  void loginbtnActionPerformed(java.awt.event.ActionEvent evt) throws Exception{
		//txtlbl.setText("Username is " + usertxt.getText() + ", Password is " + passtxt.getText());
		//System.out.println(txtlbl.getText());
        /*
		Class.forName("org.sqlite.JDBC");
	    Connection conn =
	      DriverManager.getConnection("jdbc:sqlite:/Users/hbargi/MySQLiteDB");
	    Statement stat = conn.createStatement();

	    ResultSet rs = stat.executeQuery("select * from users;");
	    while (rs.next()) {
	      if(rs.getString("username").equals(usertxt.getText()) && rs.getString("password").equals(passtxt.getText()))
	      {
	    	  txtlbl.setText("Login successful!");
	      }
	      else
	      {
	    	  txtlbl.setText("Username & password doesn't match; Please try again!");
	      }
	      //System.out.println("pass = " + rs.getString("password"));
	    }
	    rs.close();
	    conn.close();

        */
        Requester rq = new Requester();
        rq.setUserPassword(usertxt.getText() + "/" +passtxt.getText());
        rq.setSwingLoginObj(this);
        rq.run();
        System.out.println("Result is " + result);


	  }



	//method for clear button
	private  void clearbtnActionPerformed(java.awt.event.ActionEvent evt) {
		System.exit(-1);
	}


public static void main(String args[])
	{
		SwingLogin sw = new SwingLogin();
		sw.display();
	}
}

Open in new window


package Extra;

import java.io.*;
import java.net.*;
public class Provider{
	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
    static String user_password = "aaa/bbb";
	Provider(){}
	void run()
	{
		try{
			//1. creating a server socket
			providerSocket = new ServerSocket(2004, 10);
			//2. Wait for connection
			System.out.println("Waiting for connection");
			connection = providerSocket.accept();
			System.out.println("Connection received from " + connection.getInetAddress().getHostName());
			//3. get Input and Output streams
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			sendMessage("Connection successful");
			//4. The two parts communicate via the input and output streams
			do{
				try{
					message = (String)in.readObject();
					System.out.println("client>" + message);
                      if(message.equals(user_password))
                      sendMessage("Success!");
                    else sendMessage("Failure");


					if (message.equals("bye"))
						sendMessage("bye");
				}
				catch(ClassNotFoundException classnot){
					System.err.println("Data received in unknown format");
				}
			}while(!message.equals("bye"));
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
		finally{
			//4: Closing connection
			try{
				in.close();
				out.close();
				providerSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}
	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	public static void main(String args[])
	{
		Provider server = new Provider();
		while(true){
			server.run();
		}
	}
}

Open in new window


package Extra;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Requester{
	Socket requestSocket;
	ObjectOutputStream out;
 	ObjectInputStream in;
 	String message;
    String user_password;
    SwingLogin swl;

    public void setUserPassword(String s){
        user_password = s;
    }

     public void setSwingLoginObj(SwingLogin swl){
         this.swl = swl;

     }

	Requester(){}
	void run()
	{
		try{
			//1. creating a socket to connect to the server
			requestSocket = new Socket("localhost", 2004);
			System.out.println("Connected to localhost in port 2004");
			//2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			//3: Communicating with the server
			do{
				try{
					message = (String)in.readObject();
					//System.out.println("server>" + message);
					//sendMessage("Hi my server");
                      sendMessage(user_password);
                    System.out.println("message: " + message);
                    swl.setResult(message);
                      if(message.equals("Success!") || message.equals("Failure"))break;
					//message = "bye";
				//	sendMessage(message);
				}
				catch(ClassNotFoundException classNot){
					System.err.println("data received in unknown format");
				}
			}while(!message.equals("bye"));
		}
		catch(UnknownHostException unknownHost){
			System.err.println("You are trying to connect to an unknown host!");
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
		finally{
			//4: Closing connection
			try{
				in.close();
				out.close();
				requestSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}
	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	public static void main(String args[])
	{
		Requester client = new Requester();
		client.run();
	}
}

Open in new window


Output: enter aaa/bbb

Connected to localhost in port 2004
client>aaa/bbb
message: Connection successful
client>aaa/bbb
message: Success!
Result is Success!

Open in new window


Output: enter aaa/ccc

Connected to localhost in port 2004
client>aaa/ccc
message: Connection successful
client>aaa/ccc
message: Failure
Result is Failure

Open in new window

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Configuring network clients can be a chore, especially if there are a large number of them or a lot of itinerant users.  DHCP dynamically manages this process, much to the relief of users and administrators alike!
In this post we will learn different types of Android Layout and some basics of an Android App.
This video teaches viewers about errors in exception handling.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month18 days, 10 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question