Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Develop a Java Application in which TCPClient will send a text message and TCPServer will receive it

A Simple Java Application in which TCPClient will send a text message and TCPServer will receive it

In this program we have created the connection between the Client and the Socket using the client_socket and the server_socket, then we have send the message to the server using the DataOutputStream and the server will receive it using the DataInputStream. 

Java Program - 

Client.java - 

package client;

import java.io.*;

import java.net.*;


public class Client {

    private Socket client_socket = null;

    private DataOutputStream output_stream = null;


    public Client(String host_address, int port_number) throws UnknownHostException, IOException

    {

        try

        {

            client_socket = new Socket(host_address, port_number);

            System.out.println("Connected to Server");

            output_stream = new DataOutputStream(client_socket.getOutputStream());

            output_stream.writeUTF("Hello Server");

            output_stream.close();

            client_socket.close();

        }

        catch(UnknownHostException e)

        {

            System.out.println(e);

        }

        catch (IOException e) {

            System.out.println(e);

        }

    }


    public static void main(String[] args)

    {

    try

     {

         String host_address = "192.168.1.14";

         Client client = new Client(host_address,5000);

     }

     catch(UnknownHostException e)

     {

         System.out.println(e);

     }

     catch(IOException e)

     {

         System.out.println(e);

     }

    }

}


Server.java - 

package client;
import java.io.*;
import java.net.*;

public class Server {
    private ServerSocket server_socket = null;
    private Socket client_socket = null;
    private DataInputStream input_stream = null;

    public Server(int port_number) {
        try {
            server_socket = new ServerSocket(port_number);
            
            System.out.println("Server started>>");

            System.out.println("Waiting for Client>>");
            
            client_socket = server_socket.accept();
               
            System.out.println("Client accepted");

            input_stream = new DataInputStream(new BufferedInputStream((client_socket.getInputStream())));
            
            String message = input_stream.readUTF();
            
            System.out.println(message);
            
            client_socket.close();
            
            input_stream.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
        public static void main (String args[])
        {
            Server server = new Server(5000);
        }
    }


Output -



Post a Comment

0 Comments

Ad Code

Responsive Advertisement