简单的利用jdk 的socket和io流,模拟浏览器请求和响应
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Server {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket client = null;
try {
serverSocket = new ServerSocket(9999);
System.out.println("服务器初始化完毕,初始化注册端口是"+9999);
while(true){
client = serverSocket.accept();
InputStream in = client.getInputStream();
byte[] buff = new byte[1024];
int len = in.read(buff);
if(len>0){
String msg = new String(buff,0,len);
System.out.println(msg);
OutputStream os = client.getOutputStream();
SimpleDateFormat formt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuffer sb = new StringBuffer();
sb.append("HTTP/1.1 200 OK\n");
sb.append("Content-Type: text/html;charset=UTF-8\n");
sb.append("\r\n");
String html = "<html><head><title>各位朋友!</title></head><body>当前时间:"+
"<font size='14' color='blue'>"+
formt.format(new Date())+
"</font>"+
"<br/>服务器回复:<font size='14' color='blue'></font></body></html>";
sb.append(html);
os.write(sb.toString().getBytes());
os.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
main方法跑起来后, 浏览器输入 http://localhost:9999/,控制台显示:第二行开始打印的就是http请求内容
浏览器接到响应显示: