C#客户端通信通过UPD

时间:2014-08-26 02:12:43

标签: c# udp communication udpclient visual-c#-express-2010

我正在寻找一些帮助我的服务器应用程序和我的客户端之间的通信。想法是我的客户端将侦听UDP数据包,读取它然后根据它读取的内容执行命令。

我的问题是服务器发送数据包,但客户端什么都不做。 以下是我的代码片段:

客户:

public void listen()
{
        try
        {
            MessageBox.Show("");

            UdpClient receivingUdpClient = new UdpClient(11000);


            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 11000);
            try
            {

                // Blocks until a message returns on this socket from a remote host.
                Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

                string returnData = Encoding.ASCII.GetString(receiveBytes);
                string[] split = returnData.Split(':');

                if (split[0] == "SayHello")
                {
                  MessageBox.show("Hello user","Hello"); 
                }

                //Note i have many commands but i shortened it to save room. 

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
}

服务器:

else if (radioButton4.Checked)
{
        UdpClient udpClient = new UdpClient([IP_ADDRESS_HERE], 11000);
            body = richTextBox1.Text;
            title = textBox1.Text;
            Command = "Message" + ":" + body + ":" + title + ":" + 4;
            Byte[] sendBytes = Encoding.ASCII.GetBytes(Command);

            try
            {
                udpClient.Send(sendBytes, sendBytes.Length);
            }
            catch (Exception)
            {
                Console.WriteLine(e.ToString());
            }
        }

只是想看看你们是否能找到我忽略的东西。

1 个答案:

答案 0 :(得分:0)

检查您的Windows防火墙并验证它是否阻止您的客户端打开端口11000。 控制面板 - >系统和安全 - > Windows防火墙