- UID
- 31732
- 阅读权限
- 50
- 注册时间
- 2015-8-5
- 最后登录
- 1970-1-1
- 在线时间
- 小时
- 人气
- 点
- MC币
- 个
- 贡献
- 点
TA的每日心情 | 开心 2017-9-3 16:08 |
---|
签到天数: 286 天 [LV.8]以坛为家I
|
之前看到我女票发了个Java的HTTP服务器,但是我发现有个问题,访问一次以后就会卡死。。学了一段时间的Java,我也写了一个HTTP服务器
不多说了,放上代码
- package com.niconicocraft.web;
- import java.io.*;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class WebSystem extends Thread {
- private byte[] content;
- private byte[] header;
- private int port = 80;
- public static ServerSocket server;
- public OutputStream out;
- public InputStream in;
- public WebSystem(int Port) throws UnsupportedEncodingException {
- this.content = "".getBytes();//data;
- this.port = 80; //端口
- }
- public void run() {
- try {
- server = new ServerSocket(this.port);
- System.out.println("服务器运行于端口: " + server.getLocalPort());
- while (true) {
- Socket connection = null;
- try {
- connection = server.accept();
- out = new BufferedOutputStream(connection.getOutputStream());
- in = new BufferedInputStream(connection.getInputStream());
- StringBuffer request = new StringBuffer();
- while (true) {
- int c = in.read();
- if (c == '\r' || c == '\n' || c == -1) {
- break;
- }
- request.append((char) c);
- }
- if (request.indexOf("GET / ") != -1) {
- String WebString ="<h2>Niconico Craft Web System</h2>";
- showPage(WebString);
- System.out.println(request);
- } else {
- String RequestSource = request.substring(5, request.indexOf(" HTTP/"));
- String WebString;
- String header;
- }
- } catch (IOException e) {
- // TODO: handle exception
- } finally {
- if (connection != null) {
- connection.close();
- }
- }
- }
- } catch (IOException e) {
- System.err.println("无法启动HTTP服务器,端口被占用。");
- }
- }
- public static void stopserver() throws IOException {
- server.close();
- }
- public void showPage(String str) throws UnsupportedEncodingException, IOException {
- String WebString = str;
- String header = "HTTP/1.0 200 OK\r\n"
- + "Server: Niconico Craft WebServer 1.2\r\n"
- + "Content-length: " + WebString.getBytes().length + "\r\n"
- + "Content-type: text/html\r\n\r\n";
- out.write(header.getBytes("UTF-8"));
- out.write(WebString.getBytes());
- out.flush();
- }
- }
复制代码 @wx302x QWQ
|
评分
-
查看全部评分
|