如何在c#WinForms應用程序中使用UDP連接服務器客戶端?如何連接服務器客戶端與UDP?
我寫了一個控制檯applicaton服務器程序,但我需要它作爲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應用程序。我怎樣才能做到這一點 ?此外,我還需要一個客戶端代碼。