1

我正在用 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);
              }
          }
      }
  }
4

1 回答 1

2

看起来好像您希望它打印一些输出(它是通过控制台窗口)。您需要添加要在 Windows 窗体控件(例如富文本框)中显示的所有输出,然后执行以下操作:

RichTextbox1.Text += yourInput;
于 2012-04-22T16:05:09.367 回答