Monday, 30 April 2012

Socket Programing in JAVA

Socket Programing in JAVA

Using Transmission Control Protocol

Steps
Step 1) Create the following two files.
Step 2) Open command prompt.
Step 3) Compile both the files using "javac" command and run Server class first using "java" command.
Step 4) Open a new command prompt and run ClientDemo class using "java" command

Server.java


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

class Server {
    public static void main(String... x) {
        ServerSocket sock = null;
        Socket s = null;
        BufferedReader br = null;
        PrintWriter pw;
        try {
            sock = new ServerSocket(17);
            s = sock.accept();           
            do {
                System.out.println("Server is Waiting....");               
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                System.out.println("Message Received By Server is: " + br.readLine());
                //pw = new PrintWriter(s.getOutputStream());
                //pw.println("Hello Client");
                //pw.flush();
            }while (true);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            try {
                if (br != null && s != null & sock != null) {
                    br.close();
                    s.close();
                    sock.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


ClienDemo.java

 

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

class ClienDemo {
    public static void main(String... x) {

        Socket s = null;
        BufferedReader br = null;
        PrintWriter pw = null;
        String msg;

        try {
            System.out.println("My IP Address is: - " + InetAddress.getLocalHost().toString());
            s = new Socket(InetAddress.getLocalHost(), 17);
            br = new BufferedReader(new InputStreamReader(System.in));
            pw = new PrintWriter(s.getOutputStream());
            do {

                System.out.println("Enter the message that you want to send to server");
                msg = br.readLine();
                pw.println(msg + " " + (new Date()).toString() + " " + InetAddress.getLocalHost());
                pw.flush();
            } while (true);

        } catch (Exception e) {
            System.err.println("I am the ERROR " + e.getMessage());
        } finally {
            try {
                if (br != null && pw != null && s != null) {
                    br.close();
                    pw.close();
                    s.close();
                }
            } catch (Exception ce) {
                System.err.println(ce.getStackTrace());
            }
        }
    }
}

2 comments: