基于tcp/ip的简单web服务器实现

9 篇文章 0 订阅

开发环境

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();
		
	}
	

}


 

注意,在传输回给浏览器的内容中,先传递头信息

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值