Sunday, January 2, 2011

Synchronous Cilent Server application in java

Client code

Client.java

This program creates a socket connection with the server running on port 9050 on localhost and gets the input stream from the socket by chaining the BufferedReader with the InputStreamReader.


package clientserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

 public static void main(String args[]) {

  try {
   Socket s = new Socket("127.0.0.1", 9050);

   InputStreamReader streamreader = new InputStreamReader(
     s.getInputStream());
   BufferedReader br = new BufferedReader(streamreader);

   String number = br.readLine();

   System.out.println("Today's number is " + number);
   br.close();

  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}



Server code

Server.java

This program makes a ServerSocket and waits for client Requests. When a client tries to connect the server creates a new socket in a random port(using accept() method), which knows about the ip address and the port number of the client and makes the connection to the client. Also here server uses PrintWriter to sned messages to client.


package mainserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Server {

 public static void main(String args[]) {

  try {
   ServerSocket serverSock = new ServerSocket(9050);

   while (true) {

    Socket sock = serverSock.accept();
    PrintWriter pw = new PrintWriter(sock.getOutputStream());
    String TodayNum = new Server().getNumber();
    pw.println(TodayNum);
    pw.close();
    System.out.println(TodayNum);

   }

  } catch (IOException e) {
   e.printStackTrace();
  }

 }

 public String getNumber() {

  Random rg = new Random();
  int num = rg.nextInt(100);
  String numb = Integer.toString(num);
  return numb;

 }

}



Output

No comments :

Post a Comment