积木首页 | 500多种网页特效 | 函数手册 | 广播电台 | 高清晰图片素材 | 服务器合租 | 万年历 | 网友最新浏览记录
程序开发 网页设计 搜索引擎 特效代码 操作系统 防范病毒 黑客技术 图形图象 电脑硬件 网络技术 服 务 器 数 据 库 网文精粹
您的位置:积木首页 >> 程序开发频道 >> .NET >> 正文:
标题:Visual C# 2005中编写Socket网络程序(3)
时间:2006-6-21 来源:酷网动力 浏览数:
     综合运用以上阐述的使用Visual C#进行Socket网络程序开发的知识,下面的程序是一个简单的Socket通讯实例,client向server发送一段测试字符串,server接收并显示出来,给予client成功相应。
  
  //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();
    }
   }
  }
  
    以上程序在VS Express 2005 .Net2.0环境下测试通过。  


(责任编辑:笑虎)
关于本站 | 广告服务 | 联系我们 | 版权申明 | 强强联盟 | 投稿热线 | 网站地图 | 申请链接
Copyright ©2005-2006 Gimoo.net All rights reserved. 积木网 版权所有
E-mail:gimoohr@gmail.com 京ICP备05050695号