Thursday, November 16, 2006

Бичил вэб үйлчлүүлэгч, хоёрдугаар хэсэг

Энэ удаад StringBuffer обьект ашиглан үйлчлэгчээс ирэх хариуны толгойн хэсгийг уншиж байна. Уншихдаа BufferedReader обьектийг, харин хүсэлт илгээхдээ PrintWriter-ийг ашиглажээ.

Үйлчлэгчээс ирэх хариуны биеийг хэрхэн уншиж буйг бас анхаарагтун.


package web.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Logger;

/**
*
* @author
*/
public class SimpleClient {
static int PORT = 1010;
static String getHeader = "GET / HTTP/1.1";
static String agentHeader ="User-Agent: Simple Client";
static String hostHeader = "host: %s: %s";

static Logger logger = Logger.getLogger("SimpleClient");

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

String host = "localhost";
int port = PORT;

try {
host = args[0];
} catch (Exception e) {}

try {
port = Integer.parseInt(args[1]);
} catch (Exception e) {}

Socket socket = new Socket( host, port);
logger.info("started SimpleClient on port " + socket.getLocalPort());

BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));

PrintWriter out = new PrintWriter(socket.getOutputStream());

// sending get request
out.println(getHeader);
out.println(String.format(hostHeader, host, port));
out.println(agentHeader);

out.println();
out.flush();

StringBuffer header = new StringBuffer("");
StringBuffer body = new StringBuffer("");
String data;
int contentLength = 0;
int pos = 0;

// get the header
while ( (data = in.readLine()) != null) {

// the header ends at the first blank line
if (data.length() == 0)
break;

header.append(data + "\n");
pos = data.toLowerCase().indexOf("content-length:");
if (pos >= 0)
contentLength = Integer.parseInt(data.substring(pos + 15).trim());
}

// get the body, if any
if (contentLength > 0) {
try {
char[] cbuf = new char[contentLength];
in.read(cbuf);
body.append(cbuf);
} catch (Exception e) {
body.append("Error: " + e);
}
} else {
body.append("No Body information retrieved. " +
"Content-Length equals zero or was not specified.");
}

// write to the console
System.out.println("HEADER:");
System.out.println(header.toString());
System.out.println("BODY: (" + contentLength + " / " + body.length() + ")");
System.out.println(body.toString());


// close all the client streams so we can listen again
out.close();
in.close();
socket.close();

logger.info("SimpleClient ended on port " + socket.getLocalPort());
}
}

4 comments:

Зэлмэ said...

za ene chin tanidag code haragdaad baih chin yu ve. Bi sayahan neg javagiin tusul deer ajillasan yum. yag minii hiisen heseg zip file aas unshaad file ruu bichdeg heseg taarch bug garaad zovloo shuu. ZipFile, ashiglaad ZipInputStream ashiglaad shuud unshsan chin buffer dahi ugugdul ni goloosoo hudlaa oroj ireed boldoggui. araihiij zaslaa sh dee. hehe

Зэлмэ said...

Tegeed DataInputStrea, ashiglaj mur muruur ni unshaad sanaa amarsan.

Зэлмэ said...

Stream

erka said...

zip ашиглаж байсан олон хүн иймэрхүү гомдол гаргаж байсныг санах юм байна. Би өөрөө үзээгүй л дээ.

ямар ч байсан zip уншиж, бичдэг олон багаж байдгийг мэдэх юм байна.
сайнтай, муутай, бөөстэй, бөөсгүй янз бүр л байдаг байх.