using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
{
class Program
{
static void Main(string[] args)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
newsock.Bind(ipep);//Socket与本地的一个终结点相关联
Console.WriteLine("Waiting for a client.....");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
EndPoint Remote = (EndPoint)(sender);//
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetBytes(data,0,recv));
string welcome = "Welcome to my test server!";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
{
data = new byte[1024];
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
{
class Program
{
static void Main(string[] args)
{
byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区
string input, stringData;
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
data = Encoding.ASCII.GetBytes(welcome);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
Console.WriteLine("Message received from{0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
while (true)//读取数据
{
input = Console.ReadLine();//从键盘读取数据
if (input == "text")//结束标记
{
break;
}
server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//将数据发送到指定的终结点Remote
data = new byte[1024];
recv = server.ReceiveFrom(data, ref Remote);//从Remote接受数据
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
Console.WriteLine("Stopping client");
server.Close();
}
}
}