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

GitHub Copilot vs Microsoft Copilot Best AI Tool to Use in 2025

GitHub is a powerful tool used by teams and developers around the globe. This guide is…

1 day ago

Chat with Claude AI Free – Your Super-Smart AI Buddy

It's like having a super-smart buddy that is always there to help you write stories,…

5 days ago

Best Festivals UK 2025 [Free Guide Included]

The UK is known for its rich history, diverse culture, and most of all  its…

1 week ago

Bank Holidays 2025 UK – Plan Your Perfect Long Weekends

Do you have a plan for your next holiday? Being aware of the Bank Holidays within the…

1 week ago

Master Cursor AI Full Guide for Students & Creators

The world is rapidly changing of software development AI-assisted tools for coding have become the main focus. As…

1 week ago

Google Gemini AI Free AI Tool for Students & Creators

Google Gemini AI is among the top talked about developments. What exactly is it? What…

1 week ago