Thursday, 8 August 2013

Create an Output Stream - Server - In Java Socket Programming


On the server side, you can use the class PrintStream to send information to the client.
   PrintStream output;
   try {
         output = new PrintStream(serviceSocket.getOutputStream());
    }
   catch (IOException e) {
        System.out.println(e);
    }

You can use the class DataOutputStream as mentioned
   DataOutputStream output;
   try {
         output = new DataOutputStream(serviceSocket.getOutputStream());
   }
   catch (IOException e) {
         System.out.println(e);
    }


You should always close the output and input stream before you close the socket.
   try {
         output.close();
         input.close();
         MyClient.close();
   }
  catch (IOException e) {
        System.out.println(e);
  }try {
         output.close();
         input.close();
         serviceSocket.close();
         MyService.close();
    }
   catch (IOException e) {
         System.out.println(e);
   }

When programming a client, you must follow these four steps:
  1.Open a socket.
  2.Open an input and output stream to the Socket.
  3.Read from and write to the socket according to the server's protocol.
  4.Clean up.



These steps are pretty much the same for all clients. The only step that varies is step three, since it depends on the server you are talking to. 

Create Input Stream in Java Socket Programming

0 comments:

Post a Comment

Products :