欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解C# Socket編程筆記

 更新時(shí)間:2016年12月13日 15:18:20   作者:stg609  
這篇文章主要介紹了詳解C# Socket編程筆記,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧。

看到這個(gè)題目,是不是很眼熟?在博客園里搜下,保證會(huì)發(fā)現(xiàn)關(guān)于這個(gè)東東的文章實(shí)在是太多了~~~真得是沒有寫得必要,而且我也有點(diǎn)懶得去琢磨字句。(看到這,肯定得來個(gè)轉(zhuǎn)折的了,不然就看不到下文了,不是嗎)但是,為了自己下一篇要寫的文章做參考,還是有必要先補(bǔ)充一下socket基礎(chǔ)知識(shí)。

注意:如果你已經(jīng)接觸過socket,那就沒什么必要耽誤時(shí)間看下去了。另外,如果發(fā)現(xiàn)其中任何錯(cuò)誤,歡迎直接指出。

1.按慣例先來介紹下socket

Windows中的很多東西都是從Unix領(lǐng)域借鑒過來的,Socket也是一樣。在Unix中,socket代表了一種文件描述符(在Unix中一切都是以文件為單位),而這里這個(gè)描述符則是用于描述網(wǎng)絡(luò)訪問的。什么意思呢?就是程序員可以通過socket來發(fā)送和接收網(wǎng)絡(luò)上的數(shù)據(jù)。你也可以理解成是一個(gè)API。有了它,你就不用直接去操作網(wǎng)卡了,而是通過這個(gè)接口,這樣就省了很多復(fù)雜的操作。

在C#中,MS為我們提供了 System.Net.Sockets 命名空間,里面包含了Socket類。

2.有了socket,那就可以用它來訪問網(wǎng)絡(luò)了

不過你不要高興得太早,要想訪問網(wǎng)絡(luò),還得有些基本的條件(和編程無關(guān)的我就不提了):a. 要確定本機(jī)的IP和端口,socket只有與某一IP和端口綁定,才能發(fā)揮強(qiáng)大的威力。b. 得有協(xié)議吧(否則誰認(rèn)得你這發(fā)送到網(wǎng)絡(luò)的是什么呀)。想要復(fù)雜的,我們可以自己來定協(xié)議。但是這個(gè)就不在這篇里提了,我這里介紹兩種大家最熟悉不過的協(xié)議:TCP & UDP。(別說你不知道,不然...不然...我不告訴你)

如果具備了基本的條件,就可以開始用它們?cè)L問網(wǎng)絡(luò)了。來看看步驟吧:

a. 建立一個(gè)套接字

b. 綁定本機(jī)的IP和端口

c. 如果是TCP,因?yàn)槭敲嫦蜻B接的,所以要利用ListenO()方法來監(jiān)聽網(wǎng)絡(luò)上是否有人給自己發(fā)東西;如果是UDP,因?yàn)槭菬o連接的,所以來者不拒。

d. TCP情況下,如果監(jiān)聽到一個(gè)連接,就可以使用accept來接收這個(gè)連接,然后就可以利用Send/Receive來執(zhí)行操作了。而UDP,則不需要accept, 直接使用SendTo/ReceiveFrom來執(zhí)行操作。(看清楚哦,和TCP的執(zhí)行方法有區(qū)別,因?yàn)閁DP不需要建立連接,所以在發(fā)送前并不知道對(duì)方的IP和端口,因此需要指定一個(gè)發(fā)送的節(jié)點(diǎn)才能進(jìn)行正常的發(fā)送和接收)

e. 如果你不想繼續(xù)發(fā)送和接收了,就不要浪費(fèi)資源了。能close的就close吧。

如果看了上面文字,你還不清楚的話,就來看看圖好了:

面向連接的套接字系統(tǒng)調(diào)用時(shí)序

無連接的套接字系統(tǒng)調(diào)用時(shí)序

3.開始動(dòng)手敲~~代碼(簡(jiǎn)單的代碼)

首先我們來寫個(gè)面向連接的

TCPServer

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace tcpserver
 {
   /// <summary>
   /// Class1 的摘要說明。
  /// </summary>
  class server
   {
     /// <summary>
     /// 應(yīng)用程序的主入口點(diǎn)。
    /// </summary>
    [STAThread]
     static void Main(string[] args)
     {
       //
       // TODO: 在此處添加代碼以啟動(dòng)應(yīng)用程序
      //
      int recv;//用于表示客戶端發(fā)送的信息長(zhǎng)度
      byte[] data=new byte[1024];//用于緩存客戶端所發(fā)送的信息,通過socket傳遞的信息必須為字節(jié)數(shù)組
      IPEndPoint ipep=new IPEndPoint(IPAddress.Any,9050);//本機(jī)預(yù)使用的IP和端口
      Socket newsock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
       newsock.Bind(ipep);//綁定
      newsock.Listen(10);//監(jiān)聽
      Console.WriteLine("waiting for a client");
       Socket client=newsock.Accept();//當(dāng)有可用的客戶端連接嘗試時(shí)執(zhí)行,并返回一個(gè)新的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);//發(fā)送信息
      while(true)
       {//用死循環(huán)來不斷的從客戶端獲取信息
        data=new byte[1024];
         recv=client.Receive(data);
         Console.WriteLine("recv="+recv);
         if (recv==0)//當(dāng)信息長(zhǎng)度為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>
     /// 應(yīng)用程序的主入口點(diǎn)。
    /// </summary>
    [STAThread]
     static void Main(string[] args)
     {
       //
       // TODO: 在此處添加代碼以啟動(dòng)應(yīng)用程序
      //
      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);//服務(wù)器的IP和端口
      try
       {
         //因?yàn)榭蛻舳酥皇怯脕硐蛱囟ǖ姆?wù)器發(fā)送信息,所以不需要綁定本機(jī)的IP和端口。不需要監(jiān)聽。
        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();

     }
   }
 }

下面在給出無連接的(實(shí)在是太懶了,下面這個(gè)是直接復(fù)制別人的)

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);//定義一網(wǎng)絡(luò)端點(diǎn)
      Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定義一個(gè)Socket
      newsock.Bind(ipep);//Socket與本地的一個(gè)終結(jié)點(diǎn)相關(guān)聯(lián)
      Console.WriteLine("Waiting for a client..");

       IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定義要發(fā)送的計(jì)算機(jī)的地址
      EndPoint Remote = (EndPoint)(sender);//
      recv = newsock.ReceiveFrom(data, ref Remote);//接受數(shù)據(jù)      
      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];//定義一個(gè)數(shù)組用來做數(shù)據(jù)的緩沖區(qū)
      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);//將數(shù)據(jù)發(fā)送到指定的終結(jié)點(diǎn)

      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
       EndPoint Remote = (EndPoint)sender;
       data = new byte[1024];
       int recv = server.ReceiveFrom(data, ref Remote);//接受來自服務(wù)器的數(shù)據(jù)

      Console.WriteLine("Message received from{0}:", Remote.ToString());
       Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
       while (true)//讀取數(shù)據(jù)
      {
         input = Console.ReadLine();//從鍵盤讀取數(shù)據(jù)
        if (input == "text")//結(jié)束標(biāo)記
        {
           break;
         }
         server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//將數(shù)據(jù)發(fā)送到指定的終結(jié)點(diǎn)Remote
        data = new byte[1024];
         recv = server.ReceiveFrom(data, ref Remote);//從Remote接受數(shù)據(jù)
        stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
       }
       Console.WriteLine("Stopping client");
       server.Close();
     }
   }
 }   

上面的示例只是簡(jiǎn)單的應(yīng)用了socket來實(shí)現(xiàn)通信,你也可以實(shí)現(xiàn)異步socket、IP組播 等等。

MS還為我們提供了幾個(gè)助手類:TcpClient類、TcpListener類、UDPClient類。這幾個(gè)類簡(jiǎn)化了一些操作,所以你也可以利用這幾類來寫上面的代碼,但我個(gè)人還是比較習(xí)慣直接用socket來寫。

既然快寫完了,那我就再多啰嗦幾句。在需要即時(shí)響應(yīng)的軟件中,我個(gè)人更傾向使用UDP來實(shí)現(xiàn)通信,因?yàn)橄啾萒CP來說,UDP占用更少的資源,且響應(yīng)速度快,延時(shí)低。至于UDP的可靠性,則可以通過在應(yīng)用層加以控制來滿足。當(dāng)然如果可靠性要求高的環(huán)境下,還是建議使用TCP。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論