实例解析C++/CLI程序进程之间的通讯
在每一个发送与接收操作之间,我们有意延迟三秒,以便观察程序的输出。
以下是一个服务端程序使用端口2500时的输出:
Server listener blocking status is True New connection accepted Received values 42 and 69, sent result 111 Received values 66 and 71, sent result 137 Received values 7 and 93, sent result 100 Received values 43 and 65, sent result 108 Received values 45 and 3, sent result 48 Shutting down server |
而以下是对应的客户端程序,在发送5对值之后的输出:
Sent values 42 and 69, received result 111 Sent values 66 and 71, received result 137 Sent values 7 and 93, received result 100 Sent values 43 and 65, received result 108 Sent values 45 and 3, received result 48 Notified server we're shutting down Shutting down client |
套接字上的串行化
前面所演示的服务端与客户端程序以简单的方式进行数值交换,如int,然而,程序很有可能也会需要发送与接收各种不同的用户自定义的对象类型,这就涉及到串行化。
试想某些金融程序所涉及到的许多事务类型,如存款、转账、取款,每一种都与事务有关。在此,只需简单地设置好适当的串行化与反串行化机制,服务端就能处理多个客户端请求,并可返回这些事务的任意数量与任意组合。
以下有一些练习来加深对此的了解:
1、 如果一个服务端连接队列已满,那对新的客户端连接请求来说,会发生什么呢?
2、 如果当客户端还有一个打开的套接字,而服务端此时却关闭了,会发生什么呢?反之呢?
3、 试着运行一个服务端和两个客户端。我们前面说过,服务端只能处理一个客户端,为使服务端能同时处理多个客户端,需要进行多线程设计,建议对服务端作一些适当的修改,并用两个、三个、或更多客户端来测试。
4、 以下是当有两个客户端运行时的输出:
Client 2600 4 Sent values 56 and 35, received result 91 Sent values 48 and 20, received result 68 Sent values 6 and 97, received result 103 Sent values 76 and 9, received result 85 Notified server we're shutting down Shutting down client Client 2600 2 Sent values 69 and 66, received result 135 Sent values 84 and 45, received result 129 Notified server we're shutting down Shutting down client Server 2600 Waiting for new connection request New connection accepted Started thread Thread-1 Waiting for new connection request Executing thread Thread-1 Received values 56 and 35, sent result 91 New connection accepted Started thread Thread-2 Waiting for new connection request Executing thread Thread-2 Received values 69 and 66, sent result 135 Received values 48 and 20, sent result 68 Received values 84 and 45, sent result 129 Received values 6 and 97, sent result 103 Shutting down server thread Thread-2 Received values 76 and 9, sent result 85 Shutting down server thread Thread-1 |
Tags:
作者:佚名评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论