中年三次握手和四次挥手说完了,还让我手动写个HTTP协议代码( 三 )


那么我们怎么去手写一个HTTP协议呢?代码送上:
public class Server {public static void main(String[] args) throws Exception{ServerSocketChannel ssc = ServerSocketChannel.open()ssc.socket().bind(new InetSocketAddress(8080))ssc.configureBlocking(false)Selector selector = Selector.open()ssc.register(selector, SelectionKey.OP_ACCEPT)while (true){if (selector.select(3000)==0){continue}Iterator
keyIterator = selector.selectedKeys().iterator()while (keyIterator.hasNext()){SelectionKey key = keyIterator.next()new Thread(new HttpHandler(key)).run()keyIterator.remove()}}}private static class HttpHandler implements Runnable{private int bufferSize = 1024private String localCharset = "UTF-8"private SelectionKey keypublic HttpHandler(SelectionKey key){this.key=key}public void handleAccept()throws IOException{SocketChannel clientChannel = ((ServerSocketChannel)key.channel()).accept()clientChannel.configureBlocking(false)clientChannel.register(key.selector(),SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize))}@Overridepublic void run() {try {if (key.isAcceptable()){handleAccept()}if (key.isReadable()){handleRead()}}catch (IOException e){e.printStackTrace()}}public void handleRead() throws IOException{SocketChannel sc = (SocketChannel) key.channel()ByteBuffer buffer = (ByteBuffer) key.attachment()buffer.clear()if (sc.read(buffer)==-1){sc.close()}else {buffer.flip()String receiveString = Charset.forName(localCharset).newDecoder().decode(buffer).toString()String[] requestMessage = receiveString.split("")for (String s:requestMessage) {System.out.println(s)if (s.isEmpty()){break}String[] firstLine = requestMessage[0].split(" ")System.out.println()System.out.println("Method: "+firstLine[0])System.out.println("url: "+firstLine[1])System.out.println("HTTP Version: "+firstLine[2])System.out.println()StringBuffer sendString = new StringBuffer()sendString.append("HTTP/1.1 200 OK")sendString.append("Content-Type:text/htmlcharset="+localCharset+"")sendString.append("")sendString.append("")sendString.append("接受到的请求报文是:")for (String s1:requestMessage) {sendString.append(s1+"")}sendString.append("")buffer = ByteBuffer.wrap(sendString.toString().getBytes(localCharset))sc.write(buffer)sc.close()}}}}}

中年三次握手和四次挥手说完了,还让我手动写个HTTP协议代码
本文插图
这是一个简单的实现 , 只是实现思路 , 并不是真正的处理请求 , 而大家也要注意设置Content-Type的类型 , 不然容易出问题的 , 毕竟长度是有限制的 。
【来源:Java架构师之路】
声明:转载此文是出于传递更多信息之目的 。 若有来源标注错误或侵犯了您的合法权益 , 请作者持权属证明与本网联系 , 我们将及时更正、删除 , 谢谢 。邮箱地址:newmedia@xxcb.cn


推荐阅读