簡體   English   中英

如何使用UDP連接服務器客戶端?

[英]How to connect server client with UDP?

如何在c#WinForms應用程序中使用UDP連接服務器客戶端?

我已經編寫了一個控制台應用程序服務器程序,但是我需要它作為WinForms應用程序。

這是我的代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows;

namespace UDP_Server
{
class Program
{
    static void Main(string[] args) 
    {

        int recv;
        byte[] data = new byte[1024];
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 904);
        Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        newSocket.Bind(endpoint);

        Console.WriteLine("Waiting for a client...");

        IPEndPoint sender = new IPEndPoint(IPAddress.Any,904);
        EndPoint tmpRemote = (EndPoint)sender;

        recv = newSocket.ReceiveFrom(data, ref tmpRemote);


        Console.Write("Message received from {0}", tmpRemote.ToString());
        Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));

        string welcome = "Sunucuya hosgeldiniz !";
        data = Encoding.ASCII.GetBytes(welcome);

        if (newSocket.Connected)
            newSocket.Send(data);

        while (true)
        {
            if (!newSocket.Connected)
            {
                Console.WriteLine("Client Disconnected.");
                //break;
            }

            data = new byte[1024];
            recv = newSocket.ReceiveFrom(data,ref tmpRemote);

            if (recv == 0)
               // break;

            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

        }

        //newSocket.Close();

    }
}
}

我需要將此代碼更改為WinForms應用程序。 我怎樣才能做到這一點 ? 我也需要一個客戶端來編寫此代碼。

請看下面的示例項目,這些項目是使用UDP在c#表單應用程序中構建的:

對於服務器:-

http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-1/

對於客戶:

http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-2/

1.您必須將代碼移至后台線程等另一個線程,以免阻塞表單(如果不這樣做,它將顯示為無響應)。

2.您不應該使用while(true)。 使用事件接收數據,以便可以在必要時顯示它。

3.要在表單上顯示此類信息,您必須調用控件,因為它將從另一個線程調用。

對於事件,您應該在這里看看: C#SocketAsyncEventArgs處理接收和發送數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM