Issue
I've made a simple client server program in Java using Socket Programming but I'm unable to understand the basic flow of control of the program.
Client file
public static void main(String args[]) throws UnknownHostException, IOException, InterruptedException{
1. System.out.println("CLIENT: "+"client main method started");
2. Socket s=new Socket("localhost",23456);
3. BufferedWriter br=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
4. br.write("CLIENT: "+"here comes the client message");
5.br.flush();
}
Server File
public static void main(String args[]) throws IOException, InterruptedException{
11. System.out.println("Server is started");
12. ServerSocket ser=new ServerSocket(23456);
13. Socket s=ser.accept();
14. System.out.println("SERVER: "+"Server is now accepting connections");
15. System.out.println("SERVER: "+"client connected");
16. BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
17. String str=br.readLine();
18. System.out.println("SERVER: "+"Client Message: "+str);
}
It would be really helpful if someone could please explain me the flow of the program with the help of LINE NUMBERS i.e. by statement by statement.
P.S - Line number for server file starts with 11, just for sake of the convenience.
Thanks.
Solution
The way I understand it, the regular flow of any server/client application is:
The server socket is established.
The server is listening on port 23456 on incoming connections(blocking wait). Once it unblocks, the connection request that unblocked it is stored inside a Socket.
The client sends a message to the server via a Socket, which the server immediatly stores when it unblocks.
The server wakes up because it got a message (unblocks), and the Socket connection is established.
The server reads the message from the client. (If you skip this step, the client typically gets confused). This is done via the Socket accepted.
The server generates a response to the client and sends it, through a write stream of the Socket accepted.
The server closes the output stream(of the Socket accepted) to indicate end of communication. (This is required).
For a related example:
Here is a relatively simple (not really but I tried to be as explicit as I could) self contained web server that listens on port 80. Once you run it, go to http://127.0.0.1:80 to see the default page. In this program, the client is your web browser(or any other program that tries to listen on localhost 80)
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import java.awt.*;
import jserv.*;
public class JavaServer
{
public static void main(String[] args)
throws Exception
{
ServerSocket server = null;
Socket conn = null;
BufferedReader in = null;
PrintWriter out = null;
String msg = null;
ArrayList<String> tcp_get = null;
System.out.println("server> Starting!");
server = new ServerSocket(80);
while (true) {
System.out.println("server> Waiting on a connection.");
conn = server.accept();
System.out.println("server> Obtaining io handles.");
out = new PrintWriter(conn.getOutputStream(), true);
in = new BufferedReader (
new InputStreamReader (
conn.getInputStream()
)
);
System.out.println("server> We get signal.");
while ((msg = in.readLine()) != null) {
System.out.println(" " + msg);
/* done if empty line or null. */
if (msg.isEmpty()) {
System.out.println("-- all client info is read --");
break;
}
/* additional protocol handling. */
if (msg.startsWith("GET")) {
tcp_get = get_decode(msg);
}
}
System.out.println("server> sending a message to client.");
/* send the HTML data. acknowledge? */
/* header */
out.write("HTTP/1.0 200 OK\r\n");
out.write("Content-Type: text/html\r\n");
out.write("\r\n");
/* response division. */
System.out.println("tcp_get empty: " + tcp_get.isEmpty());
if (!tcp_get.isEmpty()) {
String page = tcp_get.get(0);
/* we have a page request. */
if (isValidPage(page)) {
File f = new File(page);
try {
Scanner br = new Scanner(new FileInputStream(f));
String s;
while ((s = br.nextLine()) != null) {
out.write(s + "\r\n");
}
br.close();
out.write("\r\n");
System.out.println("server> closing stream.");
} catch (FileNotFoundException e) {
out.write("<p>ERROR 404!</p>\r\n");
out.write("\r\n");
System.out.println("sent default message.");
} catch (Exception e) {}
}
/* once the stream is closed, the client will receive the data."); */
} else {
out.write("<p>Welcome to the default page!</p>\r\n");
out.write("\r\n");
}
out.close();
System.out.println("server> end of communication.");
}
}
private static boolean isValidPage(String page)
{
Pattern pat = Pattern.compile("\\w+\\.html");
Matcher mat = pat.matcher(page);
return mat.matches();
}
private static ArrayList<String> get_decode(String get)
{
ArrayList<String> tmp = new ArrayList<String>();
Pattern pat;
Matcher mat;
String page;
String page_pattern = "\\w+\\.html";
String arg_pattern = "\\w+=\\w+";
String gt = get.replaceFirst(page_pattern, "");
/* obtain the page name. */
pat = Pattern.compile(page_pattern);
mat = pat.matcher(get);
if (!mat.find()) {
System.out.println("decode> GET invalid.");
return tmp;
} else {
page = mat.group();
System.out.println("GET requests " + page);
tmp.add(page);
}
/* strip name from get. */
gt = get.replaceFirst(page_pattern, "");
/* obtain the arguments. */
pat = Pattern.compile(arg_pattern);
mat = pat.matcher(gt);
while (mat.find()) {
System.out.println("argument: " + mat.group());
tmp.add(mat.group());
}
return tmp;
}
}
In response to your actual code, please look back at this code with respect to the 7 points I listed.
import java.net.*;
import java.io.*;
class Client {
public static void main(String args[]) throws Exception {
System.out.println("client> started.");
Socket s = new Socket("localhost", 23456);
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
// all messages must end with two linefeeds.
br.write("hello, world!\n\n");
// two linefeeds with no messages indicates end.
br.write("\n\n");
// see part 7. closing the stream flushes the output.
br.close();
}
}
class Server {
public static void main(String args[]) throws Exception {
ServerSocket ser = null;
Socket s = null;
BufferedReader br = null;
String str = null;
System.out.println("server> started");
ser = new ServerSocket(23456);
s = ser.accept();
System.out.println("server> we get signal.");
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
while ((str = br.readLine()) != null) {
if (str.isEmpty()) {
System.out.println("server> everything is received.");
break;
}
System.out.println("server> got message: " + str);
}
System.out.println("server> done.");
}
}
Answered By - Dmitry
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.