日期:2014-05-18 浏览次数:20836 次
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Test2 { class Program { static void Main(string[] args) { int recv; byte[] data = new byte[1024]; //构建TCP 服务器 //得到本机IP,设置TCP端口号 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 63338); using (Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { newsock.Bind(ipep); Console.WriteLine("绑定网络地址 {0}", Dns.GetHostName()); Console.WriteLine("等待客户机连接"); IPEndPoint aaa = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)aaa; data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine("收到:" + Encoding.ASCII.GetString(data).Trim('\0')); string welcome = "Welcome ! "; data = Encoding.ASCII.GetBytes(welcome); newsock.SendTo(data, data.Length, SocketFlags.None, Remote); System.Threading.Thread.Sleep(200); } } } }
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Test { class Class1 { static void Main(string[] args) { byte[] data; string input = "hee"; string stringData; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("223.4.21.***"), 63338); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); while (true) { Console.WriteLine("请输入!"); input = Console.ReadLine(); data = Encoding.ASCII.GetBytes(input); server.SendTo(data, data.Length, SocketFlags.None, ipep); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; data = new byte[1024]; int recv = server.ReceiveFrom(data, ref Remote); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("收到:" + stringData); } } } }
public static void Main() { int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); newsock.Bind(ipep); Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine("Message received from {0}:", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); newsock.SendTo(data, data.Length, SocketFlags.None, Remote); while(true) { data = new byte[1024]; recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.ASCII.GetString(data, 0,