扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:小阳阳 来源:天极开发 2007年11月11日
关键字:
//client端 using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; namespace socketsample { class Class1 { static void Main() { try { int port = 2000; string host = "127.0.0.1"; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); c.Connect(ipe); string sendStr = "hello!This is a socket test"; byte[] bs = Encoding.ASCII.GetBytes(sendStr); c.Send(bs, bs.Length, 0); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = c.Receive(recvBytes, recvBytes.Length, 0); recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); Console.WriteLine(recvStr); c.Close(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: {0}", e); } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } Console.ReadLine(); } } } //server端 using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; namespace Project1 { class Class2 { static void Main() { try { int port = 2000; string host = "127.0.0.1"; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(ipe); s.Listen(0); Socket temp = s.Accept(); string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = temp.Receive(recvBytes, recvBytes.Length, 0); recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); Console.WriteLine(recvStr); string sendStr = "Ok!Sucess!"; byte[] bs = Encoding.ASCII.GetBytes(sendStr); temp.Send(bs, bs.Length, 0); temp.Shutdown(SocketShutdown.Both); temp.Close(); s.Shutdown(SocketShutdown.Both); s.Close(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException: {0}", e); } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } Console.ReadLine(); } } } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者