看不懂 code麻煩高手解答來源在http://www.codeproject.com/KB/IP/ChatAppAsynchUDPSocks.aspx  麻煩大家下載程式,版面有限只有顯示部份程式碼
不懂switch何時程式進入Command.Login  Command.Logout   Command.Message   Command.List找不值請高手解答using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;namespace Server
{
    //The commands for interaction between the server and the client
    enum Command
    {
        Login,      //Log into the server
        Logout,     //Logout of the server
        Message,    //Send a text message to all the chat clients
        List,       //Get a list of users in the chat room from the server
        Null        //No command
    }        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint epSender = (EndPoint)ipeSender;                serverSocket.EndReceiveFrom (ar, ref epSender);
                
                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(byteData);                //We will send this object in response the users request
                Data msgToSend = new Data();                byte [] message;
                
                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName = msgReceived.strName;                switch (msgReceived.cmdCommand)
                {
                    case Command.Login:
                        
                        //When a user logs in to the server then we add her to our
                        //list of clients                        ClientInfo clientInfo = new ClientInfo();
                        clientInfo.endpoint = epSender;      
                        clientInfo.strName = msgReceived.strName;                                                clientList.Add(clientInfo);
                        
                        //Set the text of the message that we will broadcast to all users
                        msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";   
                        break;                    case Command.Logout:                    
                        
                        //When a user wants to log out of the server then we search for her 
                        //in the list of clients and close the corresponding connection                        int nIndex = 0;
                        foreach (ClientInfo client in clientList)
                        {
                            if (client.endpoint == epSender)
                            {
                                clientList.RemoveAt(nIndex);
                                break;
                            }
                            ++nIndex;
                        }                                               
                        
                        msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";
                        break;                    case Command.Message:                        //Set the text of the message that we will broadcast to all users
                        msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                        break;                    case Command.List:                        //Send the names of all users in the chat room to the new user
                        msgToSend.cmdCommand = Command.List;
                        msgToSend.strName = null;
                        msgToSend.strMessage = null;                        //Collect the names of the user in the chat room
                        foreach (ClientInfo client in clientList)
                        {
                            //To keep things simple we use asterisk as the er to separate the user names
                            msgToSend.strMessage += client.strName + "*";   
                        }                                                message = msgToSend.ToByte();                        //Send the name of the users in the chat room
                        serverSocket.BeginSendTo (message, 0, message.Length, SocketFlags.None, epSender, 
                                new AsyncCallback(OnSend), epSender);                        
                        break;
                }                if (msgToSend.cmdCommand != Command.List)   //List messages are not broadcasted
                {
                    message = msgToSend.ToByte();                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.endpoint != epSender ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Send the message to all users
                            serverSocket.BeginSendTo (message, 0, message.Length, SocketFlags.None, clientInfo.endpoint, 
                                new AsyncCallback(OnSend), clientInfo.endpoint);                           
                        }
                    }                    txtLog.Text += msgToSend.strMessage + "\r\n";
                }                //If the user is logging out then we need not listen from her
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    //Start listening to the message send by the user
                    serverSocket.BeginReceiveFrom (byteData, 0, byteData.Length, SocketFlags.None, ref epSender, 
                        new AsyncCallback(OnReceive), epSender);
                }
            }
            catch (Exception ex)
            { 
                MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }
        }       
    }    //The data structure by which the server and the client interact with 
    //each other
    class Data
    {
        //Default constructor
        public Data()
        {
            this.cmdCommand = Command.Null;
            this.strMessage = null;
            this.strName = null;
        }        //Converts the bytes into an object of type Data
        public Data(byte[] data)
        {
            //The first four bytes are for the Command
            this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);            //The next four store the length of the name
            int nameLen = BitConverter.ToInt32(data, 4);            //The next four store the length of the message
            int msgLen = BitConverter.ToInt32(data, 8);            //This check makes sure that strName has been passed in the array of bytes
            if (nameLen > 0)
                this.strName = Encoding.UTF8.GetString(data, 12, nameLen);
            else
                this.strName = null;            //This checks for a null message field
            if (msgLen > 0)
                this.strMessage = Encoding.UTF8.GetString(data, 12 + nameLen, msgLen);
            else
                this.strMessage = null;
        }        //Converts the Data structure into an array of bytes
        public byte[] ToByte()
        {
            List<byte> result = new List<byte>();            //First four are for the Command
            result.AddRange(BitConverter.GetBytes((int)cmdCommand));            //Add the length of the name
            if (strName != null)
                result.AddRange(BitConverter.GetBytes(strName.Length));
            else
                result.AddRange(BitConverter.GetBytes(0));            //Length of the message
            if (strMessage != null)
                result.AddRange(BitConverter.GetBytes(strMessage.Length));
            else
                result.AddRange(BitConverter.GetBytes(0));            //Add the name
            if (strName != null)
                result.AddRange(Encoding.UTF8.GetBytes(strName));            //And, lastly we add the message text to our array of bytes
            if (strMessage != null)
                result.AddRange(Encoding.UTF8.GetBytes(strMessage));            return result.ToArray();
        }        public string strName;      //Name by which the client logs into the room
        public string strMessage;   //Message text
        public Command cmdCommand;  //Command type (login, logout, send message, etcetera)
    }
}

解决方案 »

  1.   

    是啊,其实switch是一个很简单的东西,lz慢慢的一步步的走走看看。。就知道其具体的操作过程了。。
      

  2.   

    我看了代码。你的意思是说switch分支何时会进入Command.Login Command.Logout Command.Message Command.List这些情况对吧。
    你的这个代码是个聊天式程序,server端会在接收来自client的请求数据包。下面这段代码你没有给出
    、serverSocket.BeginReceiveFrom (byteData, 0, byteData.Length, 
                    SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender); 
    就是这个byteData.里包含了client的请求数据包。bytedata的0到3位就是存放了Command值。
    在Data data =new Data(bytedata);构造函数里,会解析出Command值。有了Command值,那么就能确定switch分支走哪一步了。所以你要结合client程序一起调试。
      

  3.   

    了解,我試著看client資料看看 ,這人寫程式碼不錯大家可以到http://www.codeproject.com/KB/IP/ChatAppAsynchUDPSocks.aspx下載看看
      

  4.   

    谢谢你推荐的这个程式,挺好的chart学习代码。
      

  5.   

    switch 就是多个if的集合体,你只要知道msgReceived.cmdCommand执行返回的结果就知道是怎么跳转的了!
      

  6.   

    2005的能在2008上运行的,2008包含.net FrameWork2.0的。
      

  7.   

    具体流程:
      如果你接收到的消息是
       登陆行为:获得客户端的信息,并且添加到客户端列表
       登出行为:首先得到此客户端的索引,然后从客户端列表中把此客户端删除
       消息行为:得到消息,并且放到msgToSend.strMessage 里,已备进一步发送
       list行为:通过Socket异步通讯发送消息
    至于你下面的操作是进行封包、解包的