最近遇到了WCF 服务无法调用的错误,异常如下。
System.ServiceModel.ProtocolException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Error while reading message framing format at position 0 of stream (state: ReadingUpgradeRecord)
System.IO.InvalidDataException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 More data was expected, but EOF was reached.
WCF的问题一般需要对框架比较熟悉,有时难以定位。第一眼找不到原因的先 根据官方文档打开WCF日志
日志打开后发现服务端完全没有调用的记录。这时怀疑是不是调错端口了,打开资源管理器,服务正常跑着。只能再打开Wireshark记录日志,大概就是正常的3次握手,不正常的不知为何服务端主动FIN并RESET的连接。
在WCF的问题处理中,自己的日志/WCF的日志/抓包的日志都很重要。
最后的原因发现是端口被罗技升级程序占用的问题, 考虑如下示例代码
// 设置要监听的端口号
int port = 13000;
TcpListener listener = new TcpListener(IPAddress.Any, port);
TcpListener listener2 = new TcpListener(IPAddress.Loopback, port);
// 开始监听
listener.Start();
listener2.Start();
// 并不会抛出异常
Console.ReadLine();
工作久了过于相信经验,感觉一定会异常,但端口监听的是套接字,自然0.0.0.0:13000 和 127.0.0.1:13000不是一回事。
wcf的通信流程大概是这样的。
// 客户端发送服务端基地址,确认这是一个wcf的服务
client-> service: net.tcp://127.0.0.1:39100/Service
// 服务端回0b 代表确认
service-> client: 0x0b
// 客户端发送具体调用的内容
.....
由于服务端不回 0x0b
,自然会出现这样的异常。附一下异常的调用栈。事后看看也挺明显。
System.ServiceModel.Channels.ConnectionUpgradeHelper.ValidatePreambleResponse(Byte[] buffer, Int32 count, ClientFramingDecoder decoder, Uri via)
System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)
System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)
System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
...