开发环境
myEclipse 9.1
以下java代码为web服务器,返回响应信息
package com.lee.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
//监听器对象
private ServerSocket server;
/**
* 实例化,指定监端口
* @param port
*/
public Server(int port)
{
try {
//指定监听端口和最大访问数量
server = new ServerSocket(port, 10);
} catch (IOException e) {
e.printStackTrace();
}
}
public void Listener()
{
while(true)
{
try {
System.out.println("开始监听 ----- 等待数据");
//开始监听,等待数据的到来
final Socket socket = server.accept();
//新的线程
new Thread( new Runnable() {
public void run() {
PrintWriter out;
try {
out = new PrintWriter(socket.getOutputStream());
out.println("HTTP/1.1 200 OK");
out.println("Server: lee 1.0");
out.println("Content-Type:text/html;charset=gbk");
out.println("<html>");
out.println("<head>");
out.println("<title>");
out.println("这是我的服务器");
out.println("</title>");
out.println("</head>");
out.println("<body>");
out.println("hello world");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
System.out.println("传输完毕");
System.out.println("--------------------");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 入口
* @param args
*/
public static void main(String[] args) {
//设置9758为服务器监听端口
new Server(9758).Listener();
}
}
注意,在传输回给浏览器的内容中,先传递头信息