Simple Socket Program Using Java

Posted: April 22, 2009 in Java, Programming
Tags: ,

In this program, i’m using Netbeans 6.5 IDE

The client program presents a simple user interface and prompts for text input. When you click the “Send Message” button, the text is sent to the server program. The client program expects an echo from the server and prints the echo it receives on its standard output.

The server program presents a simple user interface, and when you click the “Receive Message” button, the text received from the client is displayed.

Here’s the project files :

project

And the source code …

ClientMain.java

package client;

public class ClientMain
{

    public static void main(String[] args)
    {
        ClientFrame c = new ClientFrame();
        c.setVisible(true);
        c.listenSocket();
    }

}

ClientFrame.java


package client;

import java.net.*;
import java.io.*;

public class ClientFrame extends javax.swing.JFrame
{

    public ClientFrame()
    {
        initComponents();
        line = "";
    }

    Socket socket = null;
    private BufferedReader in = null;
    private PrintWriter out = null;
    private String line = null;

    public void listenSocket()
    {
        //Create socket connection
        String serverAddress = "localhost";

        try
        {
            socket = new Socket(serverAddress, 4444);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        catch (UnknownHostException e)
        {
            System.out.println("Unknown host: " + serverAddress);
            System.exit(1);
        }
        catch  (IOException e)
        {
            System.out.println("No I/O");
            System.exit(1);
        }
}

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        sendText = new javax.swing.JTextField();
        okButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Client Side");

        jLabel1.setText("text to send over socket");

        okButton.setText("send message");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(sendText, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(okButton, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sendText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
        String text = sendText.getText();
        out.println(text);
        sendText.setText(new String(""));
        out.println(text);

        //Receive text from server
        try
        {
            String line2 = in.readLine();
            System.out.println("Text received: " + line2);
        }
        catch (IOException e)
        {
            System.out.println("Read failed");
            System.exit(1);
        }

}                                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton okButton;
    private javax.swing.JTextField sendText;
    // End of variables declaration

}

ServerMain.java


package server;

public class ServerMain
{

    public static void main(String[] args)
    {
        ServerFrame s = new ServerFrame();
        s.setVisible(true);
        s.listenSocket();
    }

}

ServerFrame.java


package server;

import java.net.*;
import java.io.*;

public class ServerFrame extends javax.swing.JFrame
{
    ServerSocket server = null;
    Socket client = null;
    BufferedReader in = null;
    PrintWriter out = null;
    String line;

    public ServerFrame()
    {
        initComponents();
        line = "";
    }    

    public void listenSocket()
    {
        int portNumber = 4444;

        try
        {
            server = new ServerSocket(portNumber);
        }
        catch (IOException e)
        {
            System.out.println("Could not listen on port " + portNumber);
            System.exit(-1);
        }

        try
        {
            client = server.accept();
        }
        catch (IOException e)
        {
            System.out.println("Accept failed :" + portNumber);
            System.exit(-1);
        }

        try
        {
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            out = new PrintWriter(client.getOutputStream(), true);
        } catch (IOException e)
        {
            System.out.println("Read failed");
            System.exit(-1);
        }

        while(true)
        {
            try
            {
                line = in.readLine();
                //Send data back to client
                out.println(line);
            }
            catch (IOException e)
            {
                System.out.println("Read failed");
                System.exit(-1);
            }
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        okButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        receivedText = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server Side");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        okButton.setText("receive message");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("text received over socket");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(receivedText, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                    .addComponent(okButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(receivedText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         

        receivedText.setText(line);
    }                                        

    private void formWindowClosed(java.awt.event.WindowEvent evt) {
        try
        {
            in.close();
            out.close();
            server.close();
        }
        catch (IOException e)
        {
            System.out.println("Could not close.");
            System.exit(-1);
        }
    }                                 

    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                new ServerFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton okButton;
    private javax.swing.JTextField receivedText;
    // End of variables declaration

}

Screenshot :

sh1

sh2

References :
http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html
http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

Comments
  1. Diana Kilel says:

    Heyy!
    Greetings from Kenya :)
    I have ran the code and its working well.
    I was wondering if there’s a way to validate the input from the client side?
    Lastly, is there a way to have both the client server textfields into one interface, say using a JPanel?
    Let me know.
    Thanx!

  2. gowtham says:

    i need coding for connecting 8 computer’s using sockets in java with a database connection just to send a message where the server should be like a centralised server for the other 7 computer’s in the lan…

  3. HARIHARAN says:

    thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s