+92 332 4229 857 99ProjectIdeas@Gmail.com

Socket Programming In Java


Socket Programming:

A socket is one endpoint of a two-way communication link between two programs running on the network.

A socket is a bi-directional communication channel between hosts (a computer on a network can be termed as a host).

A socket is bound to a port number.

A socket is an abstraction of the network similar to the way a file is an abstraction of your hard drive.

You store and retrieve data through files from hard drive without knowing the actual dynamics of the hard drive.

Similarly you send and receive data to and from network through socket without actually going into underlying mechanics.

You read from or write data to a file, using streams.

Similarly to read from or write data to a socket, you use streams.

Code

Steps – To Make a Client:

Import required Package
           import java.net.*;
           import java.io.*;
Connect / Open a Socket with Server
    Socket s = new Socket("serverAddress", "portNumber");
  For Example:
    Socket s = new Socket("192.168.103.44",333);
Get I/O Streams of Socket
    //Input Streams
        InputStream is = s.getInputStream();
        InputStreamReader isr= new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr); 

        //Output Streams
        OutputStream os = s.getOutputStream();
        PrintWriter pw = new PrintWriter(os, true);
Send / Receive Message
    //Send Message
        pw.println("hello world");

       //Receive Message
        String receiveMsg = br.readLine();
Close Socket
   s.close();


Steps – To Make a Server:

Import required Package
     import java.net.*;
     import java.io.*;
Create a Server Socket
     ServerSocket ss = new ServerSocket(portNumber);
  For Example:
     ServerSocket ss = new ServerSocket(333);
Wait for Incoming Connections
                  When connection established, communication socket is returned.
Socket s = ss.accept();
Get I/O Streams of communication Socket
    //Input Streams
        InputStream is = s.getInputStream();
        InputStreamReader isr= new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr); 

       //Output Streams
        OutputStream os = s.getOutputStream();
        PrintWriter pw = new PrintWriter(os, true);
Send / Receive Message
   //Send Message
       pw.println("hello world");

      //Receive Message
      String receiveMsg = br.readLine();
Close Socket
   s.close();

0 comments: