好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解C# Socket编程笔记

看到这个题目,是不是很眼熟?在博客园里搜下,保证会发现关于这个东东的文章实在是太多了~~~真得是没有写得必要,而且我也有点懒得去琢磨字句。(看到这,肯定得来个转折的了,不然就看不到下文了,不是吗)但是,为了自己下一篇要写的文章做参考,还是有必要先补充一下socket基础知识。

注意:如果你已经接触过socket,那就没什么必要耽误时间看下去了。另外,如果发现其中任何错误,欢迎直接指出。

1.按惯例先来介绍下socket

windows中的很多东西都是从unix领域借鉴过来的,socket也是一样。在unix中,socket代表了一种文件描述符(在unix中一切都是以文件为单位),而这里这个描述符则是用于描述网络访问的。什么意思呢?就是程序员可以通过socket来发送和接收网络上的数据。你也可以理解成是一个api。有了它,你就不用直接去操作网卡了,而是通过这个接口,这样就省了很多复杂的操作。

在c#中,ms为我们提供了 system.net.sockets 命名空间,里面包含了socket类。

2.有了socket,那就可以用它来访问网络了

不过你不要高兴得太早,要想访问网络,还得有些基本的条件(和编程无关的我就不提了):a. 要确定本机的ip和端口,socket只有与某一ip和端口绑定,才能发挥强大的威力。b. 得有协议吧(否则谁认得你这发送到网络的是什么呀)。想要复杂的,我们可以自己来定协议。但是这个就不在这篇里提了,我这里介绍两种大家最熟悉不过的协议:tcp & udp。(别说你不知道,不然...不然...我不告诉你)

如果具备了基本的条件,就可以开始用它们访问网络了。来看看步骤吧:

a. 建立一个套接字

b. 绑定本机的ip和端口

c. 如果是tcp,因为是面向连接的,所以要利用listeno()方法来监听网络上是否有人给自己发东西;如果是udp,因为是无连接的,所以来者不拒。

d. tcp情况下,如果监听到一个连接,就可以使用accept来接收这个连接,然后就可以利用send/receive来执行操作了。而udp,则不需要accept, 直接使用sendto/receivefrom来执行操作。(看清楚哦,和tcp的执行方法有区别,因为udp不需要建立连接,所以在发送前并不知道对方的ip和端口,因此需要指定一个发送的节点才能进行正常的发送和接收)

e. 如果你不想继续发送和接收了,就不要浪费资源了。能close的就close吧。

如果看了上面文字,你还不清楚的话,就来看看图好了:

面向连接的套接字系统调用时序

无连接的套接字系统调用时序

3.开始动手敲~~代码(简单的代码)

首先我们来写个面向连接的

tcpserver

?

using system;

using system.net;

using system.net.sockets;

using system.text;

 

namespace tcpserver

  {

    /// <summary>

    /// class1 的摘要说明。

   /// </summary>

   class server

    {

      /// <summary>

      /// 应用程序的主入口点。

     /// </summary>

     [stathread]

      static void main( string [] args)

      {

        //

        // todo: 在此处添加代码以启动应用程序

       //

       int recv; //用于表示客户端发送的信息长度

       byte [] data= new byte [1024]; //用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组

       ipendpoint ipep= new ipendpoint(ipaddress.any,9050); //本机预使用的ip和端口

       socket newsock= new socket(addressfamily.internetwork,sockettype.stream,protocoltype.tcp);

        newsock.bind(ipep); //绑定

       newsock.listen(10); //监听

       console.writeline( "waiting for a client" );

        socket client=newsock.accept(); //当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信

       ipendpoint clientip=(ipendpoint)client.remoteendpoint;

        console.writeline( "connect with client:" +clientip.address+ " at port:" +clientip.port);

        string welcome= "welcome here!" ;

        data=encoding.ascii.getbytes(welcome);

        client.send(data,data.length,socketflags.none); //发送信息

       while ( true )

        { //用死循环来不断的从客户端获取信息

         data= new byte [1024];

          recv=client.receive(data);

          console.writeline( "recv=" +recv);

          if (recv==0) //当信息长度为0,说明客户端连接断开

           break ;

          console.writeline(encoding.ascii.getstring(data,0,recv));

          client.send(data,recv,socketflags.none);

        }

        console.writeline( "disconnected from" +clientip.address);

        client.close();

        newsock.close();

 

      }

    }

  }

 tcpclient

?

using system;

using system.net;

using system.net.sockets;

using system.text;

 

namespace tcpclient

  {

    /// <summary>

    /// class1 的摘要说明。

   /// </summary>

   class client

    {

      /// <summary>

      /// 应用程序的主入口点。

     /// </summary>

     [stathread]

      static void main( string [] args)

      {

        //

        // todo: 在此处添加代码以启动应用程序

       //

       byte [] data= new byte [1024];

        socket newclient= new socket(addressfamily.internetwork,sockettype.stream,protocoltype.tcp);

        console.write( "please input the server ip:" );

        string ipadd=console.readline();

        console.writeline();

        console.write( "please input the server port:" );

        int port=convert.toint32(console.readline());

        ipendpoint ie= new ipendpoint(ipaddress.parse(ipadd),port); //服务器的ip和端口

       try

        {

          //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的ip和端口。不需要监听。

         newclient.connect(ie);

        }

        catch (socketexception e)

        {

          console.writeline( "unable to connect to server" );

          console.writeline(e.tostring());

          return ;

        }

        int recv = newclient.receive(data);

        string stringdata=encoding.ascii.getstring(data,0,recv);

        console.writeline(stringdata);

        while ( true )

        {

          string input=console.readline();

          if (input== "exit" )

            break ;

          newclient.send(encoding.ascii.getbytes(input));

          data= new byte [1024];

          recv=newclient.receive(data);

          stringdata=encoding.ascii.getstring(data,0,recv);

          console.writeline(stringdata);

        }

        console.writeline( "disconnect from sercer" );

        newclient.shutdown(socketshutdown.both);

        newclient.close();

 

      }

    }

  }

下面在给出无连接的(实在是太懒了,下面这个是直接复制别人的)

udpserver

?

using system;

using system.collections.generic;

using system.text;

using system.net;

using system.net.sockets;

namespace simpleudpsrvr

  {

    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); //

       recv = newsock.receivefrom(data, ref remote); //接受数据     

       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);

        while ( true )

        {

          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);

        }

      }

    }

  }

udpclient

?

using system;

using system.collections.generic;

using system.text;

using system.net;

using system.net.sockets;

namespace simpleudpclient

  {

    class program

    {

      static void main( string [] args)

      {

        byte [] data = new byte [1024]; //定义一个数组用来做数据的缓冲区

       string input, stringdata;

        ipendpoint ipep = new ipendpoint(ipaddress.parse( "127.0.0.1" ), 9050);

        socket server = new socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp);

        string welcome = "hello,are you there?" ;

        data = encoding.ascii.getbytes(welcome);

        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); //接受来自服务器的数据

 

       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();

      }

    }

  }  

上面的示例只是简单的应用了socket来实现通信,你也可以实现异步socket、ip组播 等等。

ms还为我们提供了几个助手类:tcpclient类、tcplistener类、udpclient类。这几个类简化了一些操作,所以你也可以利用这几类来写上面的代码,但我个人还是比较习惯直接用socket来写。

既然快写完了,那我就再多啰嗦几句。在需要即时响应的软件中,我个人更倾向使用udp来实现通信,因为相比tcp来说,udp占用更少的资源,且响应速度快,延时低。至于udp的可靠性,则可以通过在应用层加以控制来满足。当然如果可靠性要求高的环境下,还是建议使用tcp。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://HdhCmsTestcnblogs测试数据/stg609/archive/2008/11/15/1333889.html

dy("nrwz");

查看更多关于详解C# Socket编程笔记的详细内容...

  阅读:46次