C# code
namespace UDPServer
{
class Program
{
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
//构建TCP 服务器
//得到本机IP,设置TCP端口号
IPEndPoint ipep = new IPEndPoint( , 8001);
Socket newsock = new Socket(, , );
//绑定网络地址
(ipep);
("This is a Server, host name is {0}",());
//等待客户机连接
("Waiting for a client...");
//得到客户机IP
IPEndPoint sender = new IPEndPoint(, 0);
EndPoint Remote = (EndPoint)(sender);
recv = (data, ref Remote);
Console .WriteLine ("Message received from {0}: ", ());
Console .WriteLine (Encoding .ASCII .GetString (data ,0,recv ));
//客户机连接成功后,发送欢迎信息
string e = "e ! ";
//字符串与字节数组相互转换
data = Encoding .ASCII .GetBytes (e );
//发送信息
newsock .SendTo (data , ,SocketFlags .None ,Remote );
while (true )
{
data =new byte [1024];
//发送接受信息
recv =(data ,ref Remote);
Console .WriteLine (Encoding .ASCII .GetString (data ,0,recv));
newsock .SendTo (data ,recv ,SocketFlags .None ,Remote );
}
}
}
}
C# code
using System;
using ;
using ;
using ;
using ;
using .Sockets;
namespace UDPClient
{
class Program
{
static void Main(string[] args)
{
byte[] data = new byte[1024];
string input ,stringData;
//构建TCP 服务器
("This is a Client, host name is {0}", ());
//设置服务IP,设置TCP端口号
IPEndPoint ipep = new IPEndPoint(IPAddress .Parse ("") , 8001);
//定义网络类型,数据连接类型和网络协议UDP
Socket server = new Socket(, , );
string e = "Hello! ";
data = (e);
(data, , , ipep);
IPEndPoint sender = new IPEndPoint(, 0);
EndPoint Remote = (En
C#完整的通信代码(点对点,点对多,同步,异步,UDP,TCP) 来自淘豆网m.daumloan.com转载请标明出处.