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会报错无法执行到这一行,注释掉就行
    
    	}
    }
    
  • 相关阅读:
    java List 学习
    java Map 的学习
    samba服务
    linux常用命令
    解决粘包问题
    Python网络编程
    python异常处理
    python中封装
    python中继承和多态
    python面向对象基础
  • 原文地址:https://www.cnblogs.com/cdbb/p/12558107.html
Copyright © 2011-2022 走看看