您好,欢迎访问一九零五行业门户网

C#使用Socket创建一个小型的Web Server代码分享

这篇文章主要介绍了关于c#利用socket实现创建一个小型web server的相关资料,文中通过示例代码介绍的很详细,需要的朋友可以参考借鉴,下面来一起看看吧。
要实现了web server,通过以下几句代码浏览器访问就可以获得访问的数据。
socket socketwatch = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); socketwatch.bind(new ipendpoint(ipaddress.parse("127.0.0.1"), 81)); socketwatch.listen(20); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的。 thread thread = new thread(delegate(object obj) { socket socketlisten = (socket)obj; while (true) { socket socket = socketlisten.accept(); byte[] data = new byte[1024 * 1024 * 4]; // 浏览器发来的数据,限定为 4k。 int length = socket.receive(data, 0, data.length, socketflags.none); socket.send(encoding.utf8.getbytes("欢迎访问 www.cftea.com\r\n" + datetime.now.tostring("yyyy-mm-dd hh:mm:ss.fff"))); socket.shutdown(socketshutdown.both); socket.close(); } }); thread.isbackground = true; thread.start(socketwatch);
但以上只是原理,实际会很复杂,不过就算我们要做简单的 web server,还是需要解决两个问题:
一、输出 http 头
byte[] body = encoding.utf8.getbytes("欢迎访问 www.cftea.com\r\n" + datetime.now.tostring("yyyy-mm-dd hh:mm:ss.fff")); byte[] head = encoding.utf8.getbytes(@"http/1.1 200 ok content-length: " + body.length + @" content-type: text/plain date: " + string.format("{0:r}", datetime.now) + @" server: cftea web server "); socket.send(head); socket.send(body);
只要有特定的格式,就会被浏览器当作 http 头对待。http 头的格式为:
第一行:http/1.x + 空格 + 状态码 + 空格 + 描述
中间行:名称 + 冒号 + 空格(也可以省略) + 值
最后行:空行
格式一定要正确,否则影响浏览器对 http 头和 http 体的识别。
二、请求 http 头
到目前为止,我们还不知道浏览器中输入的 url 是什么呢。请求的 http 头也是有特定格式的,我们只需要将其获取出来,进行拆解,就可以获取 url 了。
拆解不是难事,我们说一说如何获取吧。前面的 data、length 不是一直没用么?如下:
string requesttext = encoding.utf8.getstring(data, 0, length);
完整代码
socket socketwatch = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); socketwatch.bind(new ipendpoint(ipaddress.parse("127.0.0.1"), 81)); socketwatch.listen(20); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的。 thread thread = new thread(delegate(object obj) { socket socketlisten = (socket)obj; while (true) { using (socket socket = socketlisten.accept()) { byte[] data = new byte[1024 * 1024 * 4]; // 浏览器发来的数据 int length = socket.receive(data, 0, data.length, socketflags.none); if (length > 0) { string requesttext = encoding.utf8.getstring(data, 0, length); byte[] body = encoding.utf8.getbytes(datetime.now.tostring("yyyy-mm-dd hh:mm:ss.fff")); byte[] head = encoding.utf8.getbytes(@"http/1.1 200 ok content-length: " + body.length + @" content-type: text/plain date: " + string.format("{0:r}", datetime.now) + @" server: cftea web server "); socket.send(head); socket.send(body); } socket.shutdown(socketshutdown.both); socket.close(); } } }); thread.isbackground = true; thread.start(socketwatch);
总结
以上就是c#使用socket创建一个小型的web server代码分享的详细内容。
其它类似信息

推荐信息