2.4 实践:做个聊天室

下面运用前面学到的知识,搭建聊天室。在聊天室中,某个客户端发送聊天消息,所有在线的客户端都会收到这条消息。

2.4.1 服务端

聊天室与Echo程序的不同之处在于服务端对消息的处理。服务端会遍历在线的客户端,然后推送消息。代码如下:

        //Receive回调
        public static void ReceiveCallback(IAsyncResult ar){
            try {
                ……
                  string recvStr = System.Text.Encoding.Default.GetString(state.readBuff,
    0, count);
                string sendStr = clientfd.RemoteEndPoint.ToString() + ":" + recvStr;
                byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
                foreach (ClientState s in clients.Values){
                    s.socket.Send(sendBytes);
                }
                clientfd.BeginReceive( state.readBuff, 0, 1024, 0,
                    ReceiveCallback, state);
            }
            catch (SocketException ex){
                ……
            }
        }

2.4.2 客户端

聊天客户端与Echo客户端大同小异,不同的是,它会显示以前的聊天信息。示例代码如下:

        //Receive回调
        public void ReceiveCallback(IAsyncResult ar){
            try {
                Socket socket = (Socket) ar.AsyncState;
                int count = socket.EndReceive(ar);
                string s = System.Text.Encoding.Default.GetString(readBuff, 0, count);
                recvStr = s + "\n" + recvStr;

                socket.BeginReceive( readBuff, 0, 1024, 0,
                    ReceiveCallback, socket);
            }
            catch (SocketException ex){
                Debug.Log("Socket Receive fail" + ex.ToString());
            }
        }

2.4.3 测试

现在运行多个客户端,如图2-12所示,愉快地聊天吧!

图2-12 聊天程序