zoukankan      html  css  js  c++  java
  • Java实现一个简易HTTP服务器(一)-- socket

    Java实现一个简易HTTP服务器(一)-- socket

    -----2019-9-29----------

    public class Server {
    
    	public static void main(String[] args) throws IOException {
    		ServerSocket serverSocket = new ServerSocket(89);
    		System.out.println("Server started at " + new Date() + "
    ");
    		while (true) {
    			// 通信socket的获得
    			Socket socket = serverSocket.accept();
    			System.out.println("client connected...");
    			
    			//读取数据
    			InputStream in = socket.getInputStream();
    			byte[] b = new byte[512];
    			int len = in.read(b);
    			String s = new String(b, 0, len);
    			System.out.println("" + socket.getInetAddress() + " " + socket.getPort());
    			System.out.println(s);
    
    			//返回数据
    			String res = "HTTP/1.1 200 OK
    " +
                            "Content-Type: text/html
    " + 
                            "
    " + 
                            "<html>
    " + 
                            "<head>
    "+ 
                            "<title>HTTP Server</title>
    " + 
                            "</head>
    " + 
                            "<body>
    " + 
                            "Hello HTTP!
    "+ 
                            "</body>
    " + 
                            "</html>";
    			OutputStream out = socket.getOutputStream();
    			out.write(res.getBytes());
    			
    			//关闭连接,会将in和out一起关闭
    			socket.close();
    			System.out.println("connection closed...");
    			System.out.println();
    		}
    		serverSocket.close();//ide会报错无法执行到这一行,注释掉就行
    
    	}
    }
    
  • 相关阅读:
    一则浏览器兼容性解决案例(搜狗)
    使用sass命令行,包含bourbon,neat包的项目
    指针例1
    数学建模四0-1规划
    数学建模3
    数学建模2.生产计划
    复数的实现1.3
    多文件操作1.2.5
    函数及参数类型1.2.4
    指针类型1.2.3
  • 原文地址:https://www.cnblogs.com/cdbb/p/12558107.html
Copyright © 2011-2022 走看看