C# Socket 入门3 UPD(转)
2020-12-13 14:26
阅读:427
标签:style blog http io color os ar for sp
今天来写一个UPD
1.服务端:


using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 1.创建套节字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2.填充IP
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 4321);
// 3.绑定
socket.Bind(ipe);
// 等待客户机连接
Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName());
Console.WriteLine("Waiting for a client...");
// 4.得客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint)sender;
// 5.接收客户机数据
byte[] buffer = new byte[1024];
socket.ReceiveFrom(buffer, ref remote);
Console.WriteLine(remote.ToString());
Console.WriteLine(Encoding.Unicode.GetString(buffer));
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 1.创建套节字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2.填充IP
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 4321);
// 3.绑定
socket.Bind(ipe);
// 等待客户机连接
Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName());
Console.WriteLine("Waiting for a client...");
// 4.得客户机IP
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint)sender;
// 5.接收客户机数据
byte[] buffer = new byte[1024];
socket.ReceiveFrom(buffer, ref remote);
Console.WriteLine(remote.ToString());
Console.WriteLine(Encoding.Unicode.GetString(buffer));
Console.ReadKey();
}
}
}

2.客户端


// 1.创建套节字
m_s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2.填写服务器IP
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ipe = new IPEndPoint(ip, 4321);
string welcome = "你好呀...";
byte[] data = new byte[1024];
data = Encoding.Unicode.GetBytes(welcome);
m_s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 2.填写服务器IP
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ipe = new IPEndPoint(ip, 4321);
string welcome = "你好呀...";
byte[] data = new byte[1024];
data = Encoding.Unicode.GetBytes(welcome);
// 3.发送数据
m_s.SendTo(data, data.Length, SocketFlags.None, ipe);
Console.ReadKey();
m_s.SendTo(data, data.Length, SocketFlags.None, ipe);
Console.ReadKey();

3. 效果
一样, 非常简单@
C# Socket 入门3 UPD(转)
标签:style blog http io color os ar for sp
原文地址:http://www.cnblogs.com/vonly/p/4063469.html
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:C# Socket 入门3 UPD(转)
文章链接:http://soscw.com/index.php/essay/34100.html
文章标题:C# Socket 入门3 UPD(转)
文章链接:http://soscw.com/index.php/essay/34100.html
评论
亲,登录后才可以留言!