Sunday, February 9, 2014

Use sockets in java

<<Previous   Next>>
Java - use sockets in java - Feb 28, 2010 at 16:16 PM by Vidya Sagar

Explain how to create and use sockets in java.

Sockets are created for client and server. The ServerSocket class is used for creating sockets for server. The Socket class is used for creating sockets for client side.
After creating the sockets, these sockets are utilized for both writing and writing data onto the streams. For writing data onto the output stream using client socket, the method getOutputStream() is sent as parameter to the designated output stream object, such as DataOutputStream. For reading data from the input stream using client socket, the method getInputStream() is sent as parameter to the designated inpout stream object, such as DataInputStream.
For placing data on the server socket, the method accept() is used. The result of accept() is assigned to the client socket.
Java - use sockets in java - Jan 15, 2009 at 8:10 am by Amit Satpute

Explain how to create and use sockets in java. 

Client Side:
      //creating client socket
      socket=new Socket("localhost",4000); //InetAddress.getByName ("127.0.0.1")
      //cretaing output stream for writting a data
      write=new DataOutputStream(socket.getOutputStream());
               //reading from a console
      read=new DataInputStream(System.in);
      String data=null;
            while(true)
            {
                       data=read.readLine();
                       write.writeUTF(data);
             }
Server :
//creating severSocket object.
           server=new ServerSocket(4000, 2);
           System.out.println("Socket open");
            //accept() method listens for a connection to be made to this socket and accepts it.
           client=server.accept();
           System.out.println("Client connected");
                    //receive inputs from client
           receive=new DataInputStream(client.getInputStream());
           String data=null;
            while(true)
            {
               data=receive.readUTF();
              System.out.println(data);
            }


<<Previous   Next>>

3 comments: