serversocket和serversocketchannel实现http服务

ServerSocket:

package com.http;

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {

    public static void main(String[] args) throws java.io.IOException,java.lang.InterruptedException {

        ServerSocket ss = new ServerSocket(8000);
        
        Socket socket = null;
        
        while((socket = ss.accept())!= null){
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            
            out.println("HTTP/1.1 200");
            out.println("Content-Type: text/html");
            out.println("Date: Thu, 26 Jul 2018 01:54:53 GMT");
            
            out.println();
            
            out.println("Hello

hello world aaaa

"); out.flush(); out.println(""); out.flush(); socket.shutdownOutput(); } } }

 

ServerSocketChannel:

package com.http;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class MyNioServer {

    public static void main(String[] args) throws Exception {

        ServerSocketChannel ssc = ServerSocketChannel.open();
        
        ssc.configureBlocking(false);
        
        Selector selector = Selector.open();
        
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        
        ssc.bind(new InetSocketAddress(8000));
        
        while(true){
            selector.select();
            
            Iterator it = selector.selectedKeys().iterator();
            
            while(it.hasNext()){
                SelectionKey key = it.next();
                
                if (key.isValid() && key.isAcceptable()){
                    
                    SocketChannel sc = ssc.accept();
                    
                    sc.configureBlocking(false);
                    
                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    
                    buf.put("HTTP/1.1 200\r\n".getBytes());
                    buf.put("Content-Type: text/html\r\n".getBytes());
                    buf.put("Date: Thu, 26 Jul 2018 01:54:53 GMT\r\n".getBytes());
                    buf.put("\r\n".getBytes());
                    buf.put("Hello

hello world aaaa

".getBytes()); buf.flip(); sc.write(buf); sc.shutdownOutput(); //sc.close(); } } } } }

 

转载于:https://www.cnblogs.com/lilei2blog/p/9371469.html

你可能感兴趣的:(serversocket和serversocketchannel实现http服务)