无法查看任何收到的数据

时间:2012-04-22 16:01:06

标签: c# .net udp

我用C#语言实现了非常简单的UDP服务器。

当我在基于控制台的应用程序上实现服务器时,它运行良好。

但是当我在基于Windows的应用程序上使用相同的代码实现它时,

它不像以前那样有效。

我猜这是线程问题。

所以我在代码上放了线程,但仍然无效。

“ReceiveFrom()”的功能与以前不同。

  numReceived = udpSocket.ReceiveFrom(buffer, ref remoteEP);

我错过了什么问题?

提前谢谢。

  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Windows.Forms;

  using System.Runtime.InteropServices;
  using System.Net;
  using System.Net.Sockets;
  using System.Threading;

  namespace UDP_Server
  {
      public partial class Form1 : Form
      {

          private const int portNum = 5432;

          Socket udpSocket;

          byte[] buffer = new Byte[100];

          public Form1()
          {
              InitializeComponent();
          }

          private void button1_Click(object sender, EventArgs e)
          {
              ThreadStart threadStart = new ThreadStart(onServer);
              Thread thread = new Thread(threadStart);
              thread.Start();
          }

          private void onServer()
          {
              EndPoint localEP = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.xxx"), portNum);
              //EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

              udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

              udpSocket.Bind(localEP);

              ThreadStart threadStart1 = new ThreadStart(OnReceive);
              Thread thread1 = new Thread(threadStart1);
              thread1.Start();
              //udpSocket.BeginReceiveFrom(buffer, 0, buffer.Length,
              //SocketFlags.None, ref remoteEP, new AsyncCallback(OnReceive), (object)this);
          }

          private void OnReceive()//IAsyncResult ar)
          {

              int numReceived = 0;
              EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

              Console.WriteLine("UDP Starting Server");
              Console.WriteLine("-----------------------------");

              while (true)
              {
                  numReceived = udpSocket.ReceiveFrom(buffer, ref remoteEP);

                  string s = Encoding.UTF8.GetString(buffer, 0, numReceived);

                  Console.WriteLine("Echo : {0}", s);
              }
          }
      }
  }

1 个答案:

答案 0 :(得分:2)

看起来好像你希望它打印一些输出(它是通过控制台窗口)。你需要添加你想要在Windows窗体控件(如富文本框)中显示的所有输出并执行:< / p>

RichTextbox1.Text += yourInput;