一、http协议简介
http协议规定:发送请求方:需要提供以下格式的数据给服务器:
1.1.1 请求行 加上 (\r\n)
1.1.2 请求头 加上 (\r\n)
1.1.3 请求体 加上 (\r\n)
服务方:
1.2.1 状态行 加上 (\r\n)
1.2.2 状态头 加上 (\r\n)
1.2.3 换行符号 (\r\n)
1.2.4 内容 加上 (\r\n)
状态行:通常包含 http协议版本 和http状态信息(例:200 404 500 等状态编码)
状态头:包含内容长度 内容编码
内容 :返回html内容
二、 c# socket web service 应用举例
需引用命名空间: using System.Net; using System.Net.Sockets; 代码: #region socket对外web服务器 Socket newSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); int recv; byte[] data = new byte[4096]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9008); newSock.Bind(ipep); newSock.Listen(10); while (true) { Socket tmpSocket = newSock.Accept(); try { //接收客户端消息 byte[] t = new byte[2048]; int tmpInt = tmpSocket.Receive(t); //Console.WriteLine("共接收到字节数{0}", tmpInt); //Console.WriteLine("接收内容:{0}", Encoding.ASCII.GetString(t).Trim()); //当数据接收完毕后,关闭此客户端连接 string htmlBody= "<html><head><title>test</title></head><body><h1>this is test web service:"+System.Guid.NewGuid().ToString()+"<h1></body></html>"; tmpSocket.Send(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\n")); tmpSocket.Send(Encoding.ASCII.GetBytes("Content-Type:text/html;charset=UTF-8\r\nContent-Length:" + htmlBody.Length + "\r\n")); tmpSocket.Send(Encoding.ASCII.GetBytes("\r\n")); tmpSocket.Send(Encoding.ASCII.GetBytes(htmlBody+ "!\r\n")); tmpSocket.Close(); } catch (Exception e) { Console.WriteLine("异常信息:" + e.ToString()); } } #endregion
相关阅读:
c# socket tcp 协议应用
Socket简介