[英]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.