Java

Java Socket Examples with MysqlDatabase

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.

admin

Recent Posts

Laravel 11 CRUD Mastering RESTful API MVC with Repository Pattern

In this tutorial will teach Laravel 11 Api MVC with Repository Pattern Crud Application step…

3 weeks ago

Laravel 11 CRUD Application

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

1 month ago

How to make Times Table in React

in this tutorials we will be talk about how to make a times table in…

2 months ago

Laravel Tutorial: How to Add Numbers Easily Laravel 10

In this tutorials will teach How to add two numbers in Laravel 10. (more…)

2 months ago

Build Full-Stack Node.js MongoDB CRUD App with JWT Authentication

In this tutorial, we will teach the process of building a full-stack application using Node.js,…

3 months ago

Hospital Management System using OOP Java and MySQL

In this tutorial, we will explin you through the process of building a Hospital Management…

3 months ago