产业气象站 还让我手动写个HTTP协议代码,三次握手和四次挥手说完了( 三 )


那么我们怎么去手写一个HTTP协议呢?代码送上:
publicclassServer{publicstaticvoidmain(String[]args)throwsException{ServerSocketChannelssc=ServerSocketChannel.open()ssc.socket().bind(newInetSocketAddress(8080))ssc.configureBlocking(false)Selectorselector=Selector.open()ssc.register(selector,SelectionKey.OP_ACCEPT)while(true){if(selector.select(3000)==0){continue}Iterator
keyIterator=selector.selectedKeys().iterator()while(keyIterator.hasNext()){SelectionKeykey=keyIterator.next()newThread(newHttpHandler(key)).run()keyIterator.remove()}}}privatestaticclassHttpHandlerimplementsRunnable{privateintbufferSize=1024privateStringlocalCharset="UTF-8"privateSelectionKeykeypublicHttpHandler(SelectionKeykey){this.key=key}publicvoidhandleAccept()throwsIOException{SocketChannelclientChannel=((ServerSocketChannel)key.channel()).accept()clientChannel.configureBlocking(false)clientChannel.register(key.selector(),SelectionKey.OP_READ,ByteBuffer.allocate(bufferSize))}@Overridepublicvoidrun(){try{if(key.isAcceptable()){handleAccept()}if(key.isReadable()){handleRead()}}catch(IOExceptione){e.printStackTrace()}}publicvoidhandleRead()throwsIOException{SocketChannelsc=(SocketChannel)key.channel()ByteBufferbuffer=(ByteBuffer)key.attachment()buffer.clear()if(sc.read(buffer)==-1){sc.close()}else{buffer.flip()StringreceiveString=Charset.forName(localCharset).newDecoder().decode(buffer).toString()String[]requestMessage=receiveString.split(" ")for(Strings: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("HTTPVersion:"+firstLine[2])System.out.println()StringBuffersendString=newStringBuffer()sendString.append("HTTP/1.1200OK ")sendString.append("Content-Type:text/htmlcharset="+localCharset+" ")sendString.append(" ")sendString.append("")sendString.append("接受到的请求报文是:")for(Strings1: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


推荐阅读