运行main方法后,可以接收http 请求, 适合简单的服务器测试
代码如下:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Demo02 {
public static void main(String[] args) throws IOException {
final ServerSocket serverSocket = new ServerSocket(8887);
System.out.println("server start on 8887 ...");
while (true) {
Socket acceptSocket = serverSocket.accept();
// 接收内容
BufferedReader reader = new BufferedReader(new InputStreamReader(acceptSocket.getInputStream()));
String line = reader.readLine();
System.out.println("accept : " +line);
// 返回内容
printStream(acceptSocket, "<h1>Hello World</h1>");
// 关闭流
reader.close();
acceptSocket.close();
}
}
private static void printStream(Socket acceptSocket, String test) throws IOException {
PrintStream printWriter = new PrintStream(acceptSocket.getOutputStream());
printWriter.println("HTTP/1.0 200 OK");
printWriter.println("Content-Type:text/html;charset=UTF-8");
printWriter.println();
printWriter.println(test);
printWriter.close();
}
}
编译后得到 Demo02.class, 放置到有java 环境的服务器, 执行
java Demo02
即可访问该服务器的8887 端口。
标签:printWriter,http,socket,acceptSocket,new,println,java,main From: https://www.cnblogs.com/txt1024/p/17501079.html