To make a client, process can be split into 5 steps. These are:
1. Import required package You have to import two packages
. java.net.*;
. java.io.*;
2. Connect / Open a Socket with Server
Create a client socket (communication socket)
Socket s = new Socket(“serverName”, serverPort) ;
serverName : Name or address of the server you wanted to connect such as http://www.google.com or 172.2.4.98 etc. For testing if you are running client and server on the same machine then you can specify “localhost” as the name of server .
serverPort : Port number you want to connect to The scheme is very similar to our home address and then phone number.
3. Get I/O Streams of Socket Get input & output streams connected to your socket . For reading data from socket As stated above, a socket has input stream attached to it.
InputStream is = s.getInputStream();
// now to convert byte oriented stream into character oriented buffered reader
// we use intermediary stream that helps in achieving above stated purpose
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
. For writing data to socket A socket has also output stream attached to it. Therefore,
OutputStream os = s.getOutputStream();
// now to convert byte oriented stream into character oriented print writer
// here we will not use any intermediary stream because PrintWriter constructor directly
accepts an object of OutputStream
PrintWriter pw = new PrintWriter(os, true);
Here notice that true is also passed to so that output buffer will flush.
4. Send / Receive Message Once you have the streams, sending or receiving messages isn’t a big task. It’s very much similar to the way you did with files . To send messages . To read messages
5. Close Socket pw.println(“hello world”);
String recMsg = br.readLine();
Don’t forget to close the socket, when you finished your work s.close();
0 Comments
Please add nice comments or answer ....