Home Java Java Socket Examples with MysqlDatabase

Java Socket Examples with MysqlDatabase

6 min read
0
0
2,065

This tutorial will teach you Java Socket Examples with MysqlDatabase step step.first step create the publisher class
the object of the class are used to store the rows retrieved from the database.the object of the class are stored in the vector object.

publisher class

import java.io.Serializable;

public class publisher implements Serializable {
    
    String id;
    String pname;
    String price;
    String qty;

}

Server

creating a server class using the serverSocket object.listens for a client requests for connection and returns the client Socket object establish the connection with client.retreves data from the publisher table.sends the retrieved data to the clients in the vector.

Server.java

import java.io.*;
import java.sql.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

public class Server extends Thread {

    Statement stmt=null;
    Vector records = new Vector(10,10);
    ResultSet rs = null;
    ServerSocket server = null;
    Socket client = null;
    Connection con = null;
    ObjectOutputStream out =null;
    String str = null;
    publisher pub = null;
    
    public Server()
    {
        try {
            server = new ServerSocket(1400);
            System.out.println("Starting the Server");
            start();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public void run()
    {
        while(true)
        {
            try {
                int CC;
                client = server.accept();
                System.out.println("Connection accepted");   
                out = new ObjectOutputStream(client.getOutputStream());
                System.out.println("OutputStream received");
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    con = DriverManager.getConnection("jdbc:mysql://localhost/smobile", "root","");
                    stmt = con.createStatement();
                    rs = stmt.executeQuery("select * from products");
                    records.removeAllElements();

            ResultSetMetaData RSMD = rs.getMetaData();
            CC = RSMD.getColumnCount();

                    while(rs.next())
                    {
                        pub = new publisher();
                        pub.id = rs.getString(1);
                        pub.pname = rs.getString(2);
                        pub.price = rs.getString(3);
                        pub.qty = rs.getString(4);
                        records.addElement(pub);
                        System.out.println("row returned");
                    }

                  out.writeObject(records);
                    out.close();
                    System.out.println("String returned");
                    
                    
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }
    public static void main(String args[])
{
   new Server(); 

}
}

Client

Creating a client socket an object of the socket class to establish a connection witha server.read the vector object using readObject() method sent by the server.display the output in the text area.

Client.java

import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class clientnew extends JFrame {
    
    String str;
    ResultSet rs;
    Vector records;
    GridBagLayout gb1;
    GridBagConstraints gbc;
    JScrollPane sp;
    JTextArea result;
    JLabel label;
    publisher pub;
    int i=0;
    ObjectInputStream br = null;
    Socket clientSocket = null;
    
    public clientnew()
    {
        label = new JLabel("Product Details");
        result = new JTextArea(20,60);
        str = "";
        pub = null;
        records = new Vector();
        gb1 = new GridBagLayout();
        gbc = new GridBagConstraints();
        getContentPane().setLayout(gb1);
        gbc.gridx = 0;
        gbc.gridy = 0;
        getContentPane().add(label,gbc);
          gbc.gridx = 0;
        gbc.gridy = 1;
        sp = new JScrollPane(result);
        getContentPane().add(sp,gbc);
        
        
   
            try {
                clientSocket = new Socket("localhost",1400);
                  br = new ObjectInputStream(clientSocket.getInputStream());
                  records =(Vector)br.readObject();
                  br.close();
                  result.setText("");
                  int i =0;
                  
                  result.append("ID\tPName\tPrice\tQty");
                  result.append("\n-----------------------------------------------------------------------\n");
                  
                  
                  while(i < records.size())
                  {
                      pub = (publisher)records.elementAt(i);
                      str = pub.id;
                      result.append(str + "\t");
                         str = pub.pname;
                      result.append(str + "\t");
                           str = pub.price;
                      result.append(str + "\t"); 
                             str = pub.qty;
                      result.append(str + "\n"); 
                      i++;
                      
                      
                  }
                  records.removeAllElements();
                  
                  
                    
            } catch (IOException ex) {
                Logger.getLogger(clientnew.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
            Logger.getLogger(clientnew.class.getName()).log(Level.SEVERE, null, ex);
        }
           
        
        
        
        
    }
    public static void main(String[ ] args)
	{
		clientnew server1=new clientnew();
      
                server1.setSize(500, 300); 
                server1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                server1.pack(); 
                server1.setVisible(true); 
                
	     }
}

i have attached the video link below. which will do this tutorials step by step.

Load More Related Articles
Load More By admin
Load More In Java

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Laravel 11 CRUD Application

In this tutorial will teach Laravel 11 CRUD Application step by step. Laravel  11 CRUD App…