Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Message Sender using Java Networking

This article will discuss about an application which can transfer text from client to Server via Sockets.

Introduction:

The network applications are designed in a manner so that one side is client and other is the server. Server provides some services to the clients and client uses the services provided by server. In a client side, it is assumed that a process is always running on a separate machine and is ready to provide some service therefore it can be connected to that machine. In a server side, the program starts and it waits for someone to make contact with it so that it server can provide services in order to facilitate clients. The client and server relationship is basically the request and response model. The most common implementation of this request and response model is between the web browsers and web servers in which a user enters the URL of a website to browse using a web-browser and then this request is forwarded to the web-server in order to send the webpage as a response to the client.

Description:

In this application, the text is transferred from client to server after the successful established connection. The Transmission Control Protocol (TCP) is used in this topic because it is a connection-oriented and reliable stream delivery protocol. Web browsers use this protocol to connect to web servers. This protocol is usually used in order to transfer files from one place to another.

There are some steps involved in order to establish the server and client using stream sockets and are described as:

Server:

  • Create the Socket of Server: When the socket of server is created, it means that it is ready to accept the connections on this active port. When some client is ready to make
  • Wait for a connection from client side: Client connects with the server by entering the port through socket and in order to make the request successful, the client needs to know the port of server.
  • Accept the Connection: Server accepts the connection when the client makes the request in order to communicate and get related information.
  • Message Communication: The messages are communicated once the connection is accepted by server successfully and both client as well as server can send each other messages and continue the conversation till the connection is open.
  • Close Connection to Finish Communication with specific client: Finally, after the successful communication with the client, the server can close the socket of messages and continue to listen for other clients to get connected and start communication.

Client:

  • Create the Socket of Client: The socket of client is created to make the connection with the server and get the service from the server. In order to connect with the server, the client should know the port of the server on which server is active and listening to accept the connection from the client side.
  • Connect with Server using port of Server: By giving the correct port number, the client is successfully connected with the server and initialize the message communication.
  • Message Communication: The communication of messages between both client and server is done successfully once they are connected on a specific port.
  • Close Connection and Exit: Finally the client closes the connection with the server after getting the required service from the active server on a specific port.

Overview:

In this article, the text from text-files will be transferred from client to server and this will be done in the following manner. First, the server will be waiting for the request from a client in order to establish a connection. When the client will be connected to the server then the communication process begins and the server first asks the client about the name and after confirmation asks the client to transfer the text from a text-file. The client will read the text-file and stores in a string the text and then in the form of message sends to the server. The server will receive the text and enters this text in a text-area. This process continues and the new clients keep on coming and communicating with the server. When no client appears then the server saves the text-file and this text-file will be containing all the text along with names of clients. Finally the server exits after all this process ends. The administrator can view the file and checks that how many clients were successfully communicating when the server was active. In this way, the server side is enabled in order to process the requests from maximum number of clients.

Screenshots:

Following are the screenshots from the running application:

This is the view of client side that how one sends the message to the server.

Figure 1: This is the view of client side that how one sends the message to the server.

To save all of the data in a file received from client side in a separate text file, a click on save button opens a save-dialogue box and the text is saved in the respective text-file successfully.

Figure 2: To save all of the data in a file received from client side in a separate text file, a click on save button opens a save-dialogue box and the text is saved in the respective text-file successfully.

This screen shows that the server is waiting in the active respective port for the client to make the request and so it can respond to that request by accepting the connection.

Figure 3: This screen shows that the server is waiting in the active respective port for the client to make the request and so it can respond to that request by accepting the connection.

In this screen of output, the client has connected to the server successfully and sent the message to the server from a text-file and the text is present in the text-area of client side.

Figure 4: In this screen of output, the client has connected to the server successfully and sent the message to the server from a text-file and the text is present in the text-area of client side.

Implementation & Code:

Listing 1 Save Text File Code Button Code:

try{
            String str;
            str=jTextArea1.getText();
            String filename="conversation.txt";
            File fw=new File(filename);
            FileWriter fwr=new FileWriter(fw);
            BufferedWriter bwr=new BufferedWriter(fwr);
            bwr.write(str);
            bwr.close();
            fwr.close();
            jLabel1.setVisible(true);
        	}catch(Exception ex){
            	ex.getMessage();
        	}

Listing 2 The Server Side total remaining code:

package javanetworking_server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class JavaNetworking_Server extends Thread{
    private ServerSocket welcome;    
    public JavaNetworking_Server(int port) {
        try{
        welcome = new ServerSocket(port);         
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
    public void run(){
        try{
        System.out.println("This is the Server side");
        String message_from_client;
        while (true){
        System.out.println("Waiting for the client");
        Socket socket = welcome.accept();
        System.out.println("Connection accepted");
        String message="GOODBYE";
        while(true){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        message_from_client = br.readLine();
        System.out.println("Data from client side is: "+message_from_client+"\n");
        if(message_from_client.equals(message)){
            System.exit(0);
        }
        }
        }           
        }catch(Exception e ){
            System.out.println(e.getMessage());
        }
    }
    public static void main(String[] args) {
        int port_no = 9870;
        try{
        Thread t = new JavaNetworking_Server(port_no);
        t.start();  
       SERVER s=new SERVER();//go to the main form
       s.setVisible(true);//set it visible now
        }catch(Exception ex){
            ex.getMessage();
        }
    }
}

Client Side Code:

Listing 3 Send Text Message Button Code:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        int port=9870;
	String ip="127.0.0.1";
        System.out.println("This is the Client side");         
        try{
        Socket socket =new Socket(ip,port);
        String get;
        get=jTextArea1.getText();        
        PrintWriter outtoser=new PrintWriter(socket.getOutputStream(),true);
        outtoser.println(get);
        socket.close();
        }catch (Exception e ){
         System.out.println(e.getMessage());
        }
        jLabel3.setVisible(true);
    }                                        

Listing 4 Get Text from File Button Code:

   
 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try{
        File fq=new File("E:\\Setups\\readtext.txt");//get text from this file of readtext
        FileReader wr=new FileReader(fq);        
        BufferedReader br = new BufferedReader(wr);        
        String read_data;
        while((read_data=br.readLine())!=null){
            jTextArea1.append(read_data+"\n");
        }
        br.close();
        wr.close();
        }catch(Exception ex){
            ex.getMessage();
        }
    }                                

Hope you liked it, see you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login