原网址:http://www.networkcomms.net/synchronous-send-and-receive/
对网络通讯而言,同步的请求数据并等待回复是简单而直观的。
下面的代码中,我们发送和接收一个 CustomObject类
客户端代码中,我们从服务器上同步的请求数据
try
{
//建立一个连接信息类 指定目标服务器
ConnectionInfo connectionInfo=new ConnectionInfo("127.0.0.1",10000);
//建立一个连接类
TcpConnection serverConnection=TcpConnection.GetConnection(connectionInfo);
//发送一个RequestCustomObject类型的类并同步等待直到
(1):服务器端返回一个包含CustomObject对象的CustomObjectReply类
(2):等待1秒钟,并抛出一个超时异常
CustomObject myCustomObject=serverConnection.SendReceiveObject<CustomObject>("RequestCustomObject","CustomObjectReply",1000);
}
catch(ExpectedReturnTimeoutException)
{
}
在服务器端,对客户端的同步调用、异步调用一视同仁
//添加一个包处理器,用于处理服务器收到RequestCustomObject 类型的包
//当客户端没有提供一个对象时,发送的数据设置为 GetDefault(Type)
NetworkComms.AppendGlobalIncomingpackethandler<int>("RquestCustomObject",(packetHeader,connection,input)=>
{
CustomObject myCustomObject=new CustomObject();
connection.SendObject("CustomObjectReply",myCustomObject);
});
TcpConnection.StartListening(true);
http://www.cnblogs.com/networkcomms
http://www.networkcomms.cn (官方授权中文网站) 备案审核中:)