Socket使用SOAP调用WCF
使用Socket调用WCF服务,就是要完全构造出服务调用的消息报文,服务使用的是BasicHttpBinding作为通信方式,那么就是http消息报文了,下面模拟消息报文
新建一个txt文本文档:request.txt,编写如下内容
POST /operation HTTP/1.1 Content-Type: text/xml; charset=utf-8 SOAPAction: "urlns://little.org/operation/Add" Host: localhost:8082 Content-Length: 148 Expect: 100-continue Accept-Encoding: gzip, deflate Connection: Keep-Alive <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><Add xmlns="urlns://little.org"><a>3</a><b>5</b></Add></s:Body></s:Envelope>
然后就是将这段报文发送出去,http协议是应用层协议,是基于网络层的tcp协议的,所以使用socket实现
1 public static void SocketConnect() 2 { 3 4 int port = 8081; 5 string host = "127.0.0.1"; 6 IPAddress ip = IPAddress.Parse (host); 7 IPEndPoint endpoint = new IPEndPoint (ip, port); 8 Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); 9 socket.Connect (endpoint); 10 FileStream fs = new FileStream ("request.txt", FileMode.Open); 11 StreamReader sr = new StreamReader (fs); 12 string sendMsg = sr.ReadToEnd (); 13 //string sendMsg = "Hello,Server"; 14 //System.ServiceModel.BasicHttpBinding 15 byte[] sendBuf = Encoding.UTF8.GetBytes (sendMsg); 16 socket.Send (sendBuf, sendBuf.Length, 0); 17 byte[] buf = new byte[4096]; 18 socket.Receive (buf, buf.Length, 0); 19 string msg = Encoding.UTF8.GetString (buf); 20 Console.WriteLine ("接收到来自服务器的信息..."); 21 Console.WriteLine (msg); 22 socket.Close (); 23 //socket.Shutdown(SocketShutdown.Send) 24 }
调用后返回结果报文:
HTTP/1.1 200 OK Content-Length: 172 Content-Type: text/xml; charset=utf-8 Server: Microsoft-HTTPAPI/2.0 Date: Mon, 09 Feb 2015 15:41:24 GMT <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><AddResp onse xmlns="urlns://little.org"><AddResult>8</AddResult></AddResponse></s:Body>< /s:Envelope>