国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

使用.NET訪問Internet(5) Paul_Ni(原作)(補充)

2024-07-10 13:08:11
字體:
來源:轉載
供稿:網友

異步服務器套接字示例


下面的示例程序創建一個接收來自客戶端的連接請求的服務器。該服務器是用異步套接字生成的,因此在等待來自客戶端的連接時不掛起服務器應用程序的執行。該應用程序接收來自客戶端的字符串,在控制臺顯示該字符串,然后將該字符串回顯到客戶端。來自客戶端的字符串必須包含字符串“<eof>”,以發出表示消息結尾的信號。
 [c#]
using system;
using system.net;
using system.net.sockets;
using system.text;
using system.threading;
 
// state object for reading client data asynchronously
public class stateobject {
   public socket worksocket = null;       // client  socket.
   public const int buffersize = 1024;       // size of receive buffer.
   public byte[] buffer = new byte[buffersize]; // receive buffer.
   public stringbuilder sb = new stringbuilder();  // received data string.
}
 
public class asynchronoussocketlistener {
   
   // incoming data from client.
   public static string data = null;
 
   // thread signal.
   public static manualresetevent alldone = new manualresetevent(false);
 
   public asynchronoussocketlistener() {
   }
 
   public static void startlistening() {
      // data buffer for incoming data.
      byte[] bytes = new byte[1024];
 
      // establish the local endpoint for the  socket.
      //   the dns name of the computer
      //  running the listener is "host.contoso.com".
      iphostentry iphostinfo = dns.resolve(dns.gethostname());
      ipaddress ipaddress = iphostinfo.addresslist[0];
      ipendpoint localendpoint = new ipendpoint(ipaddress, 11000);
 
      // create a tcp/ip  socket.
      socket listener = new socket(addressfamily.internetwork,
         sockettype.stream, protocoltype.tcp );
 
      // bind the  socket to the local endpoint and listen for incoming connections.
      try {
         listener.bind(localendpoint);
         listener.listen(100);
 
         while (true) {
            // set the event to  nonsignaled state.
            alldone.reset();
 
            // start  an asynchronous socket to listen for connections.
            console.writeline("waiting for a connection...");
            listener.beginaccept( 
               new asynccallback(acceptcallback),
               listener );
 
            // wait until a connection is made before continuing.
            alldone.waitone();
         }
 
      } catch (exception e) {
         console.writeline(e.tostring());
      }
 
      console.writeline("/nhit enter to continue...");
      console.read();
      
   }
 
   public static void acceptcallback(iasyncresult ar) {
      // signal the main thread to continue.
      alldone.set();
 
      // get the socket that handles the client request.
      socket listener = (socket) ar.asyncstate;
      socket handler = listener.endaccept(ar);
 
      // create the state object.
      stateobject state = new stateobject();
      state.worksocket = handler;
      handler.beginreceive( state.buffer, 0, stateobject.buffersize, 0,
         new asynccallback(readcallback), state);
   }
 
   public static void readcallback(iasyncresult ar) {
      string content = string.empty;
      
      // retrieve the state object and the handler socket
      // from the async state object.
      stateobject state = (stateobject) ar.asyncstate;
      socket handler = state.worksocket;
 
      // read data from the client socket. 
      int bytesread = handler.endreceive(ar);
 
      if (bytesread > 0) {
         // there  might be more data, so store  the data received so far.
         state.sb.append(encoding.ascii.getstring(
            state.buffer,0,bytesread));
 
         // check for end-of-file tag. if  it is not there, read 
         // more data.
         content = state.sb.tostring();
         if (content.indexof("<eof>") > -1) {
            // all the data has been read from the 
            // client. display it on the console.
            console.writeline("read {0} bytes from socket. /n data : {1}",
               content.length, content );
            // echo the data back to the client.
            send(handler, content);
         } else {
            // not all data received. get more.
            handler.beginreceive(state.buffer, 0, stateobject.buffersize, 0,
            new asynccallback(readcallback), state);
         }
      }
   }
   
   private static void send(socket handler, string data) {
      // convert the string data to byte data using ascii encoding.
      byte[] bytedata = encoding.ascii.getbytes(data);
 
      // begin sending the data to the remote device.
      handler.beginsend(bytedata, 0, bytedata.length, 0,
         new asynccallback(sendcallback), handler);
   }
 
   private static void sendcallback(iasyncresult ar) {
      try {
         // retrieve the socket from the state object.
         socket handler = (socket) ar.asyncstate;
 
         // complete sending the data to the remote device.
         int bytessent = handler.endsend(ar);
         console.writeline("sent {0} bytes to client.", bytessent);
 
         handler.shutdown(socketshutdown.both);
         handler.close();
 
      } catch (exception e) {
         console.writeline(e.tostring());
      }
   }
 
 
   public static int main(string[] args) {
      startlistening();
      return 0;
   }
}

使用 net 類的最佳做法


下列建議將幫助您最有效地使用 system.net 中包含的類:
  • 盡可能使用 webrequest 和 webresponse 而不是類型轉換為子代類。使用 webrequestwebresponse 的應用程序可以利用新的 internet 協議,而不需要進行大范圍的代碼更改。
  • 當使用 system.net 類編寫運行在服務器上的 asp.net 應用程序時,從性能的角度來看,使用 getresponse 和 getresponsestream 的異步方法通常更好。
  • 對 internet 資源打開的連接數可能對網絡性能和吞吐量有顯著的影響。默認情況下,system.net 對每個主機的每個應用程序使用兩個連接。設置應用程序的 servicepoint 中的 connectionlimit 屬性可為特定主機增加此數目。設置 servicepointmanager.defaultpersistentconnectionlimit 屬性可為所有主機增加此默認值。
  • 當編寫套接字級別的協議時,請盡可能嘗試使用 tcpclient 或 udpclient,而不是直接向 socket 中寫。這兩個客戶端類封裝 tcp 和 udp 套接字的創建,而不需要您處理連接的細節。
  • 當訪問要求憑據的站點時,請使用 credentialcache 類創建憑據的緩存而不要對每個請求都提供它們。credentialcache 類搜索緩存以查找要提供給請求的適當憑據,從而使您不必根據統一資源定位器來創建和提供憑據。

總結


    上面是vs.net中.net訪問internet的一些基本概念和代碼示例(包括訪問internet的各種方法和步驟),給大家參考一下。有任何建議請mail我 [email protected]([email protected]


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 昂仁县| 绥芬河市| 巩留县| 肥西县| 嘉善县| 双柏县| 青田县| 盐山县| 兰溪市| 无极县| 家居| 德令哈市| 布拖县| 鄂托克前旗| 西和县| 桐梓县| 龙陵县| 高安市| 邯郸县| 龙门县| 西林县| 班玛县| 垣曲县| 蒙城县| 桓仁| 华池县| 奉贤区| 常宁市| 揭西县| 密山市| 安多县| 乐至县| 自治县| 射洪县| 龙井市| 三台县| 长顺县| 姚安县| 湖北省| 鹰潭市| 灵武市|