>

Sunday, December 16, 2012

Stream Socket (using TCP) Socket Programming In Java

Stream Socket (using TCP) Socket Programming In Java

Perhaps, before you read this post you better to read my earlier post l link, perhaps you want to know what socket is?, what is socket programming?, and technically for create your code or for your comparing about method socket programming in java. or you just skip it.

Stream Socket(Using TCP)
socket programming using TCP, there is condition we must fulfill first, between server and client must establish connection first once server accept, the client can send message.

Now I will make server class first:



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
  public static void main(String[] args) throws IOException {

   ServerSocket serverSocket = new ServerSocket(3000);
   Socket client = null;

   try {
    System.out.println("waiting for request...");
    while (true) {
      client = serverSocket.accept();
      BufferedReader bufferedReader = new BufferedReader(new 
      InputStreamReader(client.getInputStream()));

      OutputStream outputStream = client.getOutputStream();
      String sentences = bufferedReader.readLine();

      System.out.println("sentences "+sentences.length());

      if(sentences.length()!= 0){
        System.out.println("message from client --- "+
        sentences);

        outputStream.write( ("\nyou have send message to"+  
        "server----"+ sentences).getBytes());

        outputStream.write("End\n".getBytes());
      }
     }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
}


and then I created client


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

public class TCPClient {
  public static void main(String[] args) throws IOException {

   BufferedReader userInput = new BufferedReader(new 
   InputStreamReader(System.in));

   String sentence = userInput.readLine();

   Socket clientSocket = null;
   OutputStream outputStream = null;
   BufferedReader bufferedReader = null;

   try {
    clientSocket = new Socket("localhost", 3000);
    outputStream = clientSocket.getOutputStream();
    bufferedReader=newBufferedReader(new 
    InputStreamReader(clientSocket.getInputStream()));

    outputStream.write((sentence + "\n").getBytes());
    outputStream.write(("End\n").getBytes());

    String reply;
    while (true) {
      reply = bufferedReader.readLine();
      if (reply.equalsIgnoreCase("End")) {
        break;
       }
      if(reply.length()!= 0){
       System.out.println("you got reply ---"+ reply);
       }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }finally{
    outputStream.close();
   bufferedReader.close();
   clientSocket.close();
  }
  }
}
both client and server has been created if you want to know technically how to run both class so can communicate each other, and interchange between console you better read my earlier post link.

Firstly I will run the server :
shabbynote run server
Server Run
 
then I run the client 
shabbynote run client
run the client

 
after I wrote in console and I press enter and the console will show like bellow
shabbynote after click enter
after click enter
 
and we check the server console , to see that our message has been sent to server:
shabbynote server response
server response
 
the best thing for using TCP that you won’t lost your package data and the sequence that won’t be unordered like in using datagram/UDP.

Saturday, December 15, 2012

DataGram/ UDP Socket Programming In Java

DataGram(UDP) Socket Programming In Java

What socket is? Socket is an interface in network to communicate between device in internet protocol, the communication are data and information interchange. So what socket programming is?, socket programming is creation application using socket API(Application Programming Interface) for interchange data. Socket application can be divided in two category based on how data sent. Data can be sent use Datagram Socket( Using UDP) or Stream Socket (using TCP). There are different treatment between UDP and TCP, even both are the same function for data interchange.

UDP Datagram Sockects in Java

in UDP connection process first for sending data, data package can be sent without need to connect first between server and client, client can can straight send data to the server. When you create server class make sure that the port is not in conflict, such as for http, database or something else. In this I use port 3000

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

class UDPServer{
    public static void main(String args[]) throws Exception{

    // determine socket and the port
          DatagramSocket serverSocket = new DatagramSocket(3000);

         // variable put data for sending and receive
         byte[] receiveData = new byte[1024];
         byte[] sendData = new byte[1024];

         while(true){
     // for reading data packet that has been sent by client
    DatagramPacket receivePacket = new DatagramPacket(receiveData,
  receiveData.length);

     serverSocket.receive(receivePacket);
     String sentence = new String( receivePacket.getData());
     System.out.println("data received from client: " + sentence);

     // this how to send datapacket to client
     // i just send back data client has been sent

      InetAddress ip = receivePacket.getAddress();
      int port = receivePacket.getPort();

   sendData = sentence.getBytes();
       DatagramPacket sendPacket = new DatagramPacket(sendData, 
   sendData.length, ip, port);
       serverSocket.send(sendPacket);
     }
    }
}
 
Now let’s create client for sending data Data, the idea is user can type any sentences in console after he or she finish typed sentences and press enter the data will send,



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClientSecond {
   public static void main(String args[]) throws Exception{
   // for retrieve sentences that that
   // has user has typed in console
    BufferedReader userInput = new BufferedReader(new 
   InputStreamReader(System.in));


   // Create socket for sending data
   DatagramSocket clientSocket = new DatagramSocket();
   InetAddress ip = InetAddress.getByName("localhost");


  // determine variable for put
  // send data and receive data
   byte[] sendData = new byte[1024];
   byte[] receiveData = new byte[1024];

  // convert sentences to byte for sending
  // to server
  String sentence = userInput.readLine();
  sendData = sentence.getBytes();

  // create data packet and send using socket
  DatagramPacket sendPacket = new DatagramPacket(sendData, 
  sendData.length, ip, 3000);
  clientSocket.send(sendPacket);

  // retrieve data send from server
  DatagramPacket receivePacket = new DatagramPacket(receiveData, 
  receiveData.length);

  clientSocket.receive(receivePacket);

  String sentencesServer = new String(receivePacket.getData());
  System.out.println("sentences from server :" 
  + sentencesServer);
  clientSocket.close();
   }
}

for running both class, because I used eclipse for making both class, you just do right click in each classes and select run as → java application, perhaps we might give a little concern how to interchange console, the are icon for interchange console and show option which console you want to see.
shabbynote console interchange
Console Interchange


I run both class
first I run server first the second I run the client. Here the screen shot :


shabbynote client input
client input text


after I click enter

shabbynote after enter
after enter



the console of server
shabbynote server response
server response


the weakness of using UDP once you send message multiple sometime the sequence message that you have been send be unordered, you can try with with code above but you send mutiple message the data be mess up. This the screen shoot result my trial :

shabby note
for multiple messages

Java I\O Part I

Input and output process are the most common things for making the application which need external data, fortunately java provide package java.io. In Java 1(version 1.0), input and output process was based on byte-oriented. It means all I/O, process was in byte form, Java version 1.1 was released, process for I/O can be manipulated by character-oriented forms too, the process more easier than byte-oriented.

Java process I/O through stream, stream was abstraction for put or obtain information. Stream can be connected to physical tools such as keyboard, file, console screen or socket. Event all tools were connected were different but how the stream work is always the same for input and output process.

Stream can use byte stream or character stream. Byte stream is used for put or retrieve data information in form byte, such as read or write file for binary file, whereas character stream is used in form character, such as for processing write and read to file texts, stream character uses Unicode character.


A. Byte Streams
I will to show how byte stream work , A program can read or write any file one byte at a time with the help of one of the subclasses of InputStream or OutputStream respectively.
For example writing a file, we Make a file with extension “. dat”.

First we make datas will be put in our file say our data is “example.dat”., what kind data you see bellow,

int[] datas = {56,230,123,43,11,37,11};

and than we import FileOutputStream from package java.io

FileOutputStream fileOutputStream = null;

the full code you see below :


import java.io.FileOutputStream;

public class ByteStreamWrittingDemo {

  public static void main(String[] args) {

     int[] datas = {56,230,123,43,11,37,11};
     FileOutputStream fileOutputStream = null;

     try {
         fileOutputStream = new FileOutputStream("example.dat");
        // start for writing to a file
         for (int i = 0; i < datas.length; i++) {
           fileOutputStream.write(datas[i]);
        }
     } catch (Exception e) {
       System.out.println(e.toString()); 
     }finally{
       // to close process so all data will be in "example.dat"
      if(fileOutputStream != null){
      try {
          fileOutputStream.close();
      } catch (Exception e2) {
          e2.printStackTrace();
        }
       }
     }
   }
}


every time you finished writing file datas to the new file don’t forget to close process as you see the code above.
If we open the file has been created the file will look like this :
shabbynote open file created
open the file that has been created


now we will make how to read binary file in java. We will use the file that we have created before,
For reading file in java, java has class FileInputStream. We can use straight use chunk code bellow

FileInputStream  input =newFileInputStream("example.dat");
int data = input .read();



our chunk code above well it isn’t recommended because reading file one byte at the time, In general, disk access is much slower than the processing performed in memory, that’s why it’s not a good idea to access disk a thousand times to read a file of 1000 bytes. To minimize the number of times the disk is accessed, Java provides so-called buffers, which serve as reservoirs of data. Here the chucnk of code

FileInputStream input = new FileInputStream("example.dat");
BufferedInputStream buffer =new BufferedInputStream(input );



The class BufferedInputStream works as a middleman between FileInputStream and the file itself. It reads a big chunk of bytes from a file into memory in one shot, and the FileInputStream object then reads single bytes from there, which is memory-to-memory operations. BufferedOutputStream works similarly with the class FileOutputStream. The main idea here is to minimize disk access.
in process reading file in java after finish read whole content file will return value “-1”, this fact sometimes is used for terminating iteration in reading file process.

the full code you will see bellow

import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class ByteStreamReadDemo {
  public static void main(String[] args) {
   FileInputStream input = null;
   BufferedInputStream buffer = null;
   try {
    input = new FileInputStream("example.dat");
    buffer = new BufferedInputStream(input);

    boolean stopIterate = false;
    while (!stopIterate) {
      int byteValue = buffer.read();
      System.out.print(byteValue +" ");
      if(byteValue == -1){
        stopIterate =true;
       }
    }
   } catch (Exception e) {
    System.out.println(e.toString());
  }finally{
    if(input != null){
      try {
         buffer.close();
         input.close();
       } catch (Exception e2) {
       // TODO: handle exception
        e2.printStackTrace();
        }
     }
   }
  }
}

 

While reading a stream with the help of BufferedInputStream you watch for the end-of-file character. But when you write a stream via BufferedOutputStream with method write(), you need to do one extra step. Call the method flush() before closing the buffered stream. This ensures that none of the buffered bytes “get stuck” and that all are written out to the underlying output stream. 
You might be wondering, how large is the buffer? While the default buffer size varies depending on the OS, you can control it using a two-argument constructor. For example, to set the buffer size to 5000 bytes instantiate the buffered stream as BufferedInputStream buff = new BufferedInputStream(myFile, 5000);

Java I\O Part II

In the previous post we have try how byte streams process, now we continue for character oriented, how it work same but have different class.

A. Character Streams
Text in java presented as set char which values two-byte characters, based on unicode standard, some of the standard charsets are US-ASCII, UTF-8, and UTF-16. The Java classes FileReader and FileWriter were specifically created to work with text files, but they work only with default character encoding and don’t handle localization properly. According the best way is to pipe class InputStreamReader with specified encoding and the FileInputStream then InputStreamReader reads bytes and decodes them into characters using a specified CharSet, for FileOutputStream and OutputStreamWriter are same treatment as FileInputStream. The class InputStreamReader .

Let’s try for writing a text file, we determine what we will put in our text file :

String myWrting ="Hi guys! This is my file text"

we use FileOutputStream and OutputStreamWriter, I pipe The class FileOutputStream reads bytes and decodes them into characters using a specified CharSet. “UTF8”

FileOutputStream myFile = new FileOutputStream("myWrting.txt");
Writer out = new BufferedWriter(new OutputStreamWriter(myFile,"UTF8"));

and here its our full code,

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class WrittingTxtDemo {

public static void main(String[] args) {
 try {
 String myWrting ="Hi guys! This is my file text";
 FileOutputStream myFile = new FileOutputStream("myWrting.txt");

 Writer writer = new BufferedWriter(new  
 OutputStreamWriter(myFile, "UTF8"));

  writer.write(myWrting);
  writer.flush();
  writer.close();

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



you may open the file we have created by notepad, and the contain will the same as we put in the code above.

Now we create how to read file text file in java, reads bytes from a text file and converts them from UTF-8 encoding into Unicode to return results as a String, I recommended uses StringBuffer that usually works faster than String when it comes to performing text manipulations. I used file that has been created before.


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class ReadingTxtDemo {
public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer();

  try {
    FileInputStream myFile = new FileInputStream("myWrting.txt");
    InputStreamReader input = new InputStreamReader(myFile,  
    "UTF8");
    Reader reader = new BufferedReader(input);
 
     int ch;
   
     while ((ch = reader.read())> -1) {
      buffer.append((char) ch);
     }

      buffer.toString();
      System.out.println("The file contains : "+buffer);
     } catch (Exception e) {
      System.out.println(e);
     }
   }
}