UDP 服务器端

public void Start()
  {
    if(!m_IsRunning)
    {
        try
        {
            m_UdpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);                
            IPEndPoint ipep=new IPEndPoint(IPAddress.Any,(int)Port);  //程序另一处对Port赋值8000
            m_UdpServer.Bind(ipep);
            m_DataReceiveProcThread = new Thread(new ThreadStart(DataReceiveProc));   //用线程调用接受数据的方法
            m_IsRunning = true;
            m_DataReceiveProcThread.Start();

         }

        catch{……}

    }

  }

其中

void DataReceiveProc() 
    {   
        while(m_IsRunning) 
        {    
           try
           {
                byte[] data = new byte[BufferSize];      
                m_UdpServer.Receive(data);             //data是客户端发来的信息
                MessageBox.Show(data.ToString());

           }

          catch(……)

       }

    }

以上摘录了核心方法,在main函数中为这个类创建一个对象,再调用start方法即可执行。最近CSDN出现问题,其实我有个疑问曾有人问过:客户端可以用UdpClient,服务器端用什么类定义?看来没有其它类可以定义服务器,还是只好用Socket,只是Protocol用UDP,数据类型用DataGram。另外,与TCP不同的是UDP服务器端的IPAddress是Any,因为是广播式通信。

参考资料:http://www.cnblogs.com/nehu/articles/218512.html

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s