import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.TimerTask;

/**
 * @author Adrian BER (beradrian@yahoo.com)
 */
public class PopupAnkit extends JPanel implements ActionListener{

   private JToggleButton invokePopupButton;
    private JFrame popupWindow;
    Statement stmt=null;
    ResultSet rs=null;
   // int tempCount=0;
    
    
    public static int count=0;
    /**
     * Constructor.
     */
    public PopupAnkit() {
        init();
    }

    /**
     * Initialiser.
     */
    private void init() {

    	  invokePopupButton = new JToggleButton("Show popup");
    	try
		{
    	
    		int tempData=0;
    		Class.forName("com.mysql.jdbc.Driver");
    		String serverName = "173.255.216.128:3306"; 
        	String mydatabase = "chat"; 
        	String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url 
        	String username = "root"; 
        	String password = "***"; 
        	Connection conn = DriverManager.getConnection(url, username, password); 
    		stmt= conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    		rs=stmt.executeQuery("select count(*) from ajax_chat_messages");
    		
    		rs.next();
			
			count=Integer.parseInt(rs.getString(1));
    		
		}
    	catch(Exception e)
    	{
    		System.out.println("e-------"+e);
    	}
    	
    	Timer t=new Timer(1000*45,this);
    	TimerTask t1=new TimerTask(){
    		
			@Override
			public void run() 
			{
				
			}};
    	
    	
    	
      
       // invokePopupButton.addActionListener(this);
        
           

        // add components to main panel
        this.setLayout(new BorderLayout());
        this.add(invokePopupButton, BorderLayout.EAST);

        // use frame
        popupWindow = new JFrame();
        popupWindow.setUndecorated(true);

        popupWindow.addWindowFocusListener(new WindowFocusListener() {
            public void windowGainedFocus(WindowEvent e) {
            	
            }

            public void windowLostFocus(WindowEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (popupWindow.isVisible())
                        	popupWindow.setVisible(false);
                    }
                });
            }
        });

        // add some components to window
        popupWindow.getContentPane().setLayout(new BorderLayout());
        ((JComponent)popupWindow.getContentPane()).setBorder(BorderFactory.createEtchedBorder());
        JTextField aTextField = new JTextField(10);
        popupWindow.getContentPane().add(new JLabel("New Message"), BorderLayout.WEST);
        t.start();
        //popupWindow.getContentPane().add(aTextField);
        popupWindow.pack();
    }

    public static void main(String[] args) {
        JFrame mainFrame = new JFrame("PopupWindow");
        mainFrame.getContentPane().add(new PopupAnkit());
        mainFrame.pack();
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(false);
    }


    public void actionPerformed(ActionEvent e)
    {
    			
		try
		{
		
			rs=stmt.executeQuery("select count(*) from ajax_chat_messages");
    		rs.next();
    		int tempData = rs.getInt(1);
    		System.out.println("Temp---"+tempData);
    		System.out.println("Count---"+count);
    		
    		if(tempData>count)
    		{
    			
    			   if (!popupWindow.isVisible()) 
    			   {
    				  
    		            // set location relative to button
    		            Point location = invokePopupButton.getLocation();
    		            SwingUtilities.convertPointToScreen(location, invokePopupButton.getParent());
    		            location.translate(0, invokePopupButton.getHeight()
    		                    + (invokePopupButton.getBorder() == null ? 0
    		                        : invokePopupButton.getBorder().getBorderInsets(invokePopupButton).bottom));
    		            popupWindow.setLocation(location);

    		            // show the popup if not visible
    		            invokePopupButton.setText("Hide popup");
    		            popupWindow.setVisible(true);
    		            popupWindow.requestFocus();
    		            count++;
    		        } 
    			   else
    		        {
    		            // hide it otherwise
    		            invokePopupButton.setText("Show popup");
    		            popupWindow.setVisible(false);
    		        }
    			
    		}
    		
		}
		catch(Exception e1)
		{
		System.out.println("Error--"+e1);	
		}
    }
}

Hi friends....
I try to connect with mysql (port-3306). Above code works properly in localhost but when i try it with ip of my server () it gives following error

e-------com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: 

** BEGIN NESTED EXCEPTION ** 

java.net.ConnectException
MESSAGE: Connection refused: connect

STACKTRACE:

java.net.ConnectException: Connection refused: connect
	at java.net.PlainSocketImpl.socketConnect(Native Method)
	at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
	at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
	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:218)
	at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
	at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271)
	at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
	at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
	at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
	at java.sql.DriverManager.getConnection(DriverManager.java:582)
	at java.sql.DriverManager.getConnection(DriverManager.java:185)
	at PopupAnkit.init(PopupAnkit.java:46)
	at PopupAnkit.<init>(PopupAnkit.java:27)
	at PopupAnkit.main(PopupAnkit.java:111)


** END NESTED EXCEPTION **



Last packet sent to the server was 16 ms ago.
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException
Error--java.lang.NullPointerException

I can't understand why it not connects with my remote mysql. Though same program works perfectly in localhost.
Any help???
Please....
Thanks in advance

Dani AI

Generated

Quick diagnosis for : "Connection refused" means the TCP handshake to port 3306 was rejected — either nothing is listening on the server IP:port, a firewall/security group is blocking the port, or MySQL is bound only to loopback. pointed at configuration changes and suggested reachability checks; follow the steps below in order to narrow the cause.

Try these from your client machine first, then run the server-side checks if the client can't reach the port:

# from your client
ping 173.255.216.128
nc -vz 173.255.216.128 3306    # or: telnet 173.255.216.128 3306
mysql -h 173.255.216.128 -P 3306 -u root -p
# on the server
sudo ss -ltnp | grep 3306
sudo grep -E "bind-address|skip-networking" /etc/mysql* -R || true
sudo systemctl status mysql     # or: sudo service mysql status
sudo iptables -L -n | grep 3306 || sudo ufw status

If the server is listening only on 127.0.0.1, edit the MySQL config (my.cnf / mysqld.cnf) and change or comment out the bind-address line, ensure skip-networking is not set, then restart MySQL (e.g., sudo systemctl restart mysql). Do not give root remote access — create a dedicated DB user restricted to your client IP:

-- in the mysql shell
GRANT ALL PRIVILEGES ON chat.* TO 'chatuser'@'your.client.ip' IDENTIFIED BY 'strongpassword';
FLUSH PRIVILEGES;

If you cannot or should not open 3306 to the internet, use an SSH tunnel instead:

ssh -L 3307:localhost:3306 user@173.255.216.128
# then point JDBC to jdbc:mysql://localhost:3307/chat

Finally, the many NullPointerExceptions you saw are a downstream effect: conn, stmt or rs were null after the failed connect. Check for null before using them, close resources in finally (or use try-with-resources), and run DB work off the Swing event thread (SwingWorker) so the UI stays responsive.

Recommended Answers

All 4 Replies

Remove servers like your personal installation are by default these days enabled only for localhost. That mean that only application that is on that machine can access it. If you want to get remote access then you need to change configuration (danger of mistakenly exposing your database to whole world without proper security) or you need to build a service that will serve data on request (web services approach)

Remove servers like your personal installation are by default these days enabled only for localhost. That mean that only application that is on that machine can access it. If you want to get remote access then you need to change configuration (danger of mistakenly exposing your database to whole world without proper security) or you need to build a service that will serve data on request (web services approach)

Can you tell me how i can do it???/

Do what? Config changes or web service?

> I try to connect with mysql (port-3306). Above code works properly in localhost but when i try it with ip of my server () it gives following error

This seems like a configuration issue. Are you able to ping this host? Are you able to connect to this host via a SQL UI client like MySQL workbench? Is the server under your control or have you bought this MySQL hosting?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.