最MC论坛
标题:
[Java]简单的HTTP服务器
[打印本页]
作者:
Jianghao7172
时间:
2017-5-23 18:53
标题:
[Java]简单的HTTP服务器
之前看到我女票发了个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
作者:
Summer大大
时间:
2017-5-24 09:37
所以说有什么用呢?
作者:
lss233
时间:
2017-5-24 21:17
嘛...只能接受一个连接的http服务器
不过有一个可以一起写代码的对象我还是羡慕的
羡慕一脸.jpg
作者:
V乐乐
时间:
2017-5-25 12:03
Nice...
额,只能有一个连接吗
欢迎光临 最MC论坛 (http://www.zuimc.com/)
Powered by Discuz! X3.2