Akashic Records

Java 네트워크 - 4 본문

오래된글/Java

Java 네트워크 - 4

Andrew's Akashic Records 2018. 4. 9. 11:07
728x90

7. 서버 소켓


서버의 기본적인 라이프 사이클

1. 새로운 ServerSocket은 ServerSocket() 생성자를 사용하여 특정한 포트에서 생성된다.

2. ServerSocket은 accept()메쏘드를 사용해서 특정한 포트로 들어오는 연결 요청신호에 귀를 기울인다. accept()는 클라이언트가 연결 요청 신호를 보낼 때까지 봉쇄(block)되다가. 신호를 받으면 서버와 클라이언트를 연결하는 Socket 객체를 반환한다.

3. 서버의 유형에 따라서 클라이언트와 통신하는 입출력 스트림을 얻기 위해 Socket의 getInputStream(), getOutputStream(), 또는 두 메쏘드가 함께 호출된다.

4. 서버와 클라이언트는 연결이 끊길 때까지 합의된 프로토콜에 따라 대화를 한다.

5. 서버, 클라이언트 또는 양쪽에서 연결을 끊는다.

6. 서버는 2단계로 돌아가, 다음 연결을 기다린다.

① package network.net.httpserver;

② import java.net.*;

③ import java.io.*;

④ import java.util.*;

⑥ public class HttpServerConsole extends Thread {

⑧ static StringBuffer theData = new StringBuffer();

⑨ static String ContentType;

⑩ static int ContentLength;

⑪ Socket theConnection;

⑬ public static void main(String[] args) {

⑭ int thePort;

⑮ ServerSocket ss;

16 Socket theConnection;

17 FileInputStream theFile;

18

19 try{

20 theFile = new FileInputStream(args[0]);

21 BufferedReader bre = new BufferedReader(new InputStreamReader(theFile));

22 if(((args[0].toLowerCase()).endsWith(".html")) || ((args[0].toLowerCase()).endsWith(".htm"))) {

23 ContentType = "text/html";

24 } else {

25 C

26 }

27

28 try{

29 String thisLine = "";

30 while ((thisLine = bre.readLine()) != null) {

31 theData.append(thisLine+"\n");

32 }

33 } catch (Exception e) {

34 System.err.println(e);

35 }

36 } catch (Exception e) {

37 System.err.println(e);

38 System.err.println("Usage : java network.net.httpserver.HttpServerConsole FILENAME PORT");

39 System.exit(1);

40 }

41

42 try{

43 thePort = Integer.parseInt(args[1]);

44 if(thePort < 0 || thePort > 65535) thePort = 80;

45 } catch(Exception e) {

46 thePort = 80;

47 }

48

49 try{

50 ss= new ServerSocket(thePort);

51 System.out.println("Accepting connections on port "+ss.getLocalPort());

52 System.out.println("Data to be sent : ");

53 System.out.println(theData.toString());

54 while(true) {

55 HttpServerConsole hserver = new HttpServerConsole(ss.accept());

56 hserver.start();

57 }

58 } catch(IOException e) {}

59 }

60

61 public HttpServerConsole(Socket s) {

62 theConnection = s;

63 }

64

65 public HttpServerConsole() {

66 }

67

68 public void run() {

69 try{

70 PrintStream os = new PrintStream(theConnection.getOutputStream());

71 BufferedReader is =

72 new BufferedReader(new InputStreamReader(theConnection.getInputStream()));

73 String request = is.readLine();

74 if(request.indexOf("HTTP/") != -1) {

75 while(true) {

76 String thisLine = is.readLine();

77 if(thisLine.trim().equals("")) break;

78 }

79 os.print("HTTP/1.0 200 OK\r\n");

80 Date now = new Date();

81 os.print("Date:"+now+"\r\n");

82 os.print("Server:HttpServerConsole\r\n");

83 os.print("Content-length:"+ContentLength+"\r\n");

84 os.print("Content-type:"+ContentType+"\r\n\r\n");

85 }

86 os.println(theData.toString());

87 theConnection.close();

88 } catch(IOException e){}

89 }

90 }


완전판 HTTP Server

① package network.net.httpserver;

② import java.net.*;

③ import java.io.*;

④ import java.util.*;

⑥ public class JHTTP extends Thread {

⑧ private File documentRootDirectory;

⑨ private String indexFileName = "index.html";

⑩ private ServerSocket server;

⑪ private int numThreads = 50;

⑬ public JHTTP(File documentRootDirectory, int port,String indexFileName) throws IOException {

⑮ if (!documentRootDirectory.isDirectory()) {

16 throw new IOException(documentRootDirectory+ " does not exist as a directory");

17 }

18 this.documentRootDirectory = documentRootDirectory;

19 this.indexFileName = indexFileName;

20 this.server = new ServerSocket(port);

21 }

22

23 public JHTTP(File documentRootDirectory, int port)

24 throws IOException {

25 this(documentRootDirectory, port, "index.html");

26 }

27

28 public JHTTP(File documentRootDirectory) throws IOException {

29 this(documentRootDirectory, 80, "index.html");

30 }

31

32 public void run() {

33 for (int i = 0; i < numThreads; i++) {

34 Thread t = new Thread(new RequestProcessor(documentRootDirectory, indexFileName));

35 t.start();

36 }

37 System.out.println("Accepting connections on port "+ server.getLocalPort());

38 System.out.println("Document Root: " + documentRootDirectory);

39 while (true) {

40 try {

41 Socket request = server.accept();

42 RequestProcessor.processRequest(request);

43 } catch (IOException e) {}

44 }

45 }

46

47 public static void main(String[] args) {

48 File docroot;

49 try {

50 docroot = new File(args[0]);

51 } catch (ArrayIndexOutOfBoundsException e) {

52 System.out.println("Usage: java JHTTP docroot port indexfile");

53 return;

54 }

55

56 int port;

57 try {

58 port = Integer.parseInt(args[1]);

59 if (port < 0 || port > 65535) port = 80;

60 } catch (Exception e) {

61 port = 80;

62 }

63

64 try {

65 JHTTP webserver = new JHTTP(docroot, port);

66 webserver.start();

67 } catch (IOException e) {

68 System.out.println("Server could not start because of an "+ e.getClass());

69 System.out.println(e);

70 }

71 }

72 }

73

74 package network.net.httpserver;

75

76 import java.net.*;

77 import java.io.*;

78 import java.util.*;

79

80 public class RequestProcessor implements Runnable {

81

82 private static List pool = new LinkedList();

83 private File documentRootDirectory;

84 private String indexFileName = "index.html";

85

86 public RequestProcessor(File documentRootDirectory,String indexFileName) {

87

88 // 루트가 파일이면 에러 발생

89 if (documentRootDirectory.isFile()) {

90 throw new IllegalArgumentException("documentRootDirectory must be a directory, not a file");

91 }

92 this.documentRootDirectory = documentRootDirectory;

93 try {

94 this.documentRootDirectory = documentRootDirectory.getCanonicalFile();

95 } catch (IOException e) {}

96

97 if (indexFileName != null) this.indexFileName = indexFileName;

98 }

99

100 public static void processRequest(Socket request) {

101 synchronized (pool) {

102 pool.add(pool.size(), request);

103 pool.notifyAll();

104 }

105 }

106

107 public void run() {

108 String root = documentRootDirectory.getPath();

109 while (true) {

110 Socket connection;

111 synchronized (pool) {

112 while (pool.isEmpty()) {

113 try {

114 pool.wait();

115 } catch (InterruptedException e) {}

116 }

117 connection = (Socket) pool.remove(0);

118 }

119 try {

120 String filename;

121 String contentType;

122 OutputStream raw = new BufferedOutputStream(connection.getOutputStream());

123 Writer out = new OutputStreamWriter(raw);

124 Reader in =

125 new InputStreamReader(new BufferedInputStream(connection.getInputStream()),"ASCII");

126 StringBuffer requestLine = new StringBuffer();

127 int c;

128 while (true) {

129 c = in.read();

130 if (c == '\r' || c == '\n') break;

131 requestLine.append((char) c);

132 }

133 String get = requestLine.toString();

134 System.out.println(get);

135 StringTokenizer st = new StringTokenizer(get);

136 String method = st.nextToken();

137 String version = "";

138

139 if (method.equals("GET")) {

140 filename = st.nextToken();

141 if (filename.endsWith("/")) filename += indexFileName;

142 contentType = guessContentTypeFromName(filename);

143 if (st.hasMoreTokens()) {

144 version = st.nextToken();

145 }

146 File theFile = new File(documentRootDirectory,

147 filename.substring(1,filename.length()));

148

149 if (theFile.canRead() && theFile.getCanonicalPath().startsWith(root)) {

150 DataInputStream fis =

151 new DataInputStream(new BufferedInputStream(new FileInputStream(theFile)));

152 byte[] theData = new byte[(int) theFile.length()];

153 fis.readFully(theData);

154 fis.close();

155

156 if (version.startsWith("HTTP/")) {

157 out.write("HTTP/1.0 200 OK\r\n");

158 Date now = new Date();

159 out.write("Date: " + now + "\r\n");

160 out.write("Server: JHTTP 1.0\r\n");

161 out.write("Content-length: " + theData.length + "\r\n");

162 out.write("Content-type: " + contentType + "\r\n\r\n");

163 out.flush();

164 }

165 raw.write(theData);

166 raw.flush();

167 } else {

168 if (version.startsWith("HTTP/")) {

169 out.write("HTTP/1.0 404 File Not Found\r\n");

170 Date now = new Date();

171 out.write("Date: " + now + "\r\n");

172 out.write("Server: JHTTP 1.0\r\n");

173 out.write("Content-type: text/html\r\n\r\n");

174 }

175 out.write("<HTML>\r\n");

176 out.write("<HEAD><TITLE>File Not Found</TITLE>\r\n");

177 out.write("</HEAD>\r\n");

178 out.write("<BODY>");

179 out.write("<H1>HTTP Error 404: File Not Found</H1>\r\n");

180 out.write("</BODY></HTML>\r\n");

181 out.flush();

182 }

183 } else {

184 if (version.startsWith("HTTP/")) {

185 out.write("HTTP/1.0 501 Not Implemented\r\n");

186 Date now = new Date();

187 out.write("Date: " + now + "\r\n");

188 out.write("Server: JHTTP 1.0\r\n");

189 out.write("Content-type: text/html\r\n\r\n");

190 }

191 out.write("<HTML>\r\n");

192 out.write("<HEAD><TITLE>Not Implemented</TITLE>\r\n");

193 out.write("</HEAD>\r\n");

194 out.write("<BODY>");

195 out.write("<H1>HTTP Error 501: Not Implemented</H1>\r\n");

196 out.write("</BODY></HTML>\r\n");

197 out.flush();

198 }

199 } catch (IOException e) {

200 } finally {

201 try {

202 connection.close();

203 } catch (IOException e) {}

204 }

205 }

206 }

207

208 public static String guessContentTypeFromName(String name) {

209 if (name.endsWith(".html") || name.endsWith(".htm")) {

210 return "text/html";

211 } else if (name.endsWith(".txt") || name.endsWith(".java")) {

212 return "text/plain";

213 } else if (name.endsWith(".gif")) {

214 return "image/gif";

215 } else if (name.endsWith(".class")) {

216 return "application/octet-stream";

217 } else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) {

218 return "image/jpeg";

219 } else return "text/plain";

220 }

221 }


728x90

'오래된글 > Java' 카테고리의 다른 글

Java 네트워크 - 6  (0) 2018.04.09
Java 네트워크 - 5  (0) 2018.04.09
Java 네트워크 - 3  (0) 2018.04.09
Java 네트워크 - 2  (0) 2018.04.09
Java 네트워크 - 1  (0) 2018.04.09
Comments