基于socket - TCP 编写简单http服务器
socket 监听
package cn.noybzy;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author noybzy
*/
public class SocketService {
ServerSocket serverSocket;
public static void main(String[] args){
//创建socket服务器
try {
serverSocket = new ServerSocket(5656);
while(true){
//等待连接
Socket socket = serverSocket.accept();
Thread t = new Thread(new SocketThread(socket));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
线程处理请求
package cn.noybzy;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* @author noybzy
*/
public class SocketThread implements Runnable {
private Socket socket;
InputStreamReader inputStreamReader;
InputStream inputStream;
OutputStream outputStream;
OutputStreamWriter outputStreamWriter;
public SocketThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
// 获取输入流
inputStream = socket.getInputStream();
// 将字节流转换成字符流(utf-8)
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
char[] chars = new char[20];
int len;
StringBuffer stringBuffer = new StringBuffer();
while ((len = inputStreamReader.read(chars)) != -1 && inputStreamReader.ready()) {
stringBuffer.append(chars, 0, len);
}
int i = stringBuffer.indexOf("\r\n");
System.out.println(stringBuffer.substring(0,i));
outputStream = socket.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8");
String data = "<html><body><h1>Hello, world!</h1></body></html>";
//响应头
outputStreamWriter.write("HTTP/1.1 200 OK\r\n");
//响应行
outputStreamWriter.write("Connection: close\r\n");
outputStreamWriter.write("Content-Type: text/html\r\n");
// 响应体
outputStreamWriter.write("\r\n");
outputStreamWriter.write(data);
outputStreamWriter.flush();
} catch (
IOException e) {
e.printStackTrace();
} finally {
if (outputStreamWriter != null) {
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
最后效果