中年三次握手和四次挥手说完了,还让我手动写个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()}}}}}
本文插图
这是一个简单的实现 , 只是实现思路 , 并不是真正的处理请求 , 而大家也要注意设置Content-Type的类型 , 不然容易出问题的 , 毕竟长度是有限制的 。
【来源:Java架构师之路】
声明:转载此文是出于传递更多信息之目的 。 若有来源标注错误或侵犯了您的合法权益 , 请作者持权属证明与本网联系 , 我们将及时更正、删除 , 谢谢 。邮箱地址:newmedia@xxcb.cn
推荐阅读
- 中年美国寸土寸金,为何要在纽约建立林则徐广场?原因很简单
- 中年北斗系统发言人答封面新闻:北斗定位精度最好可达1点几米
- 中年检测设备行业政策及环境
- 中年元春回府省亲为何会在夜晚进行?原来其中大有文章
- 中年北斗三号全球服务可用性达99%以上,全球范围定位精度优于10米
- 奖励|广西侗乡小学连续三次期末发活鱼奖励学生
- 锁定|起底电信诈骗“杀猪盘”:锁定中年女性,先培养感情再骗钱
- 中年做了几道硬菜,孩子们的胃口很大,可以无限量地吃
- 中年你吃火锅,我吃火锅底料——做的川味慢烤牛肋排
- 教育|每一位中年女性,都是“乘风破浪的姐姐”