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

首頁 > 編程 > .NET > 正文

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

2024-07-10 13:08:11
字體:
供稿:網(wǎng)友

同步客戶端套接字示例


下面的示例程序創(chuàng)建一個連接到服務(wù)器的客戶端。該客戶端是用同步套接字生成的,因此掛起客戶端應(yīng)用程序的執(zhí)行,直到服務(wù)器返回響應(yīng)為止。該應(yīng)用程序?qū)⒆址l(fā)送到服務(wù)器,然后在控制臺顯示該服務(wù)器返回的字符串。
 [c#]
using system;
using system.net;
using system.net.sockets;
using system.text;
 
public class synchronoussocketclient {
 
  public static void startclient() {
    // data buffer for incoming data.
    byte[] bytes = new byte[1024];
 
    // connect to a remote device.
    try {
      // establish the remote endpoint for the socket.
      //    the name of the
      //   remote device is "host.contoso.com".
      iphostentry iphostinfo = dns.resolve("host.contoso.com");
      ipaddress ipaddress = iphostinfo.addresslist[0];
      ipendpoint remoteep = new ipendpoint(ipaddress,11000);
 
      // create a tcp/ip  socket.
      socket sender = new socket(addressfamily.internetwork, 
        sockettype.stream, protocoltype.tcp );
 
      // connect the socket to the remote endpoint. catch any errors.
      try {
        sender.connect(remoteep);
 
        console.writeline("socket connected to {0}",
          sender.remoteendpoint.tostring());
 
        // encode the data string into a byte array.
        byte[] msg = encoding.ascii.getbytes("this is a test<eof>");
 
        // send the data through the  socket.
        int bytessent = sender.send(msg);
 
        // receive the response from the remote device.
        int bytesrec = sender.receive(bytes);
        console.writeline("echoed test = {0}",
          encoding.ascii.getstring(bytes,0,bytesrec));
 
        // release the socket.
        sender.shutdown(socketshutdown.both);
        sender.close();
        
      } catch (argumentnullexception ane) {
        console.writeline("argumentnullexception : {0}",ane.tostring());
      } catch (socketexception se) {
        console.writeline("socketexception : {0}",se.tostring());
      } catch (exception e) {
        console.writeline("unexpected exception : {0}", e.tostring());
      }
 
    } catch (exception e) {
      console.writeline( e.tostring());
    }
  }
  
  public static int main(string[] args) {
    startclient();
    return 0;
  }
}

同步服務(wù)器套接字示例


下面的示例程序創(chuàng)建一個接收來自客戶端的連接請求的服務(wù)器。該服務(wù)器是用同步套接字生成的,因此在等待來自客戶端的連接時不掛起服務(wù)器應(yīng)用程序的執(zhí)行。該應(yīng)用程序接收來自客戶端的字符串,在控制臺顯示該字符串,然后將該字符串回顯到客戶端。來自客戶端的字符串必須包含字符串“<eof>”,以發(fā)出表示消息結(jié)尾的信號。
 [c#]
using system;
using system.net;
using system.net.sockets;
using system.text;
 
public class synchronoussocketlistener {
  
  // incoming data from the client.
  public static string data = null;
 
  public static void startlistening() {
    // data buffer for incoming data.
    byte[] bytes = new byte[1024];
 
    // establish the local endpoint for the  socket.
    //  dns.gethostname returns the name of the 
    // host running the application.
    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(10);
 
      // start listening for connections.
      while (true) {
        console.writeline("waiting for a connection...");
        // program is suspended while waiting for an incoming connection.
        socket handler = listener.accept();
        data = null;
 
        // an incoming connection needs to be processed.
        while (true) {
          bytes = new byte[1024];
          int bytesrec = handler.receive(bytes);
          data += encoding.ascii.getstring(bytes,0,bytesrec);
          if (data.indexof("<eof>") > -1) {
            break;
          }
        }
 
        // show the data on the console.
        console.writeline( "text received : {0}", data);
 
        // echo the data back to the client.
        byte[] msg = encoding.ascii.getbytes(data);
 
        handler.send(msg);
        handler.shutdown(socketshutdown.both);
        handler.close();
      }
      
    } catch (exception e) {
      console.writeline(e.tostring());
    }
 
    console.writeline("/nhit enter to continue...");
    console.read();
    
  }
 
  public static int main(string[] args) {
    startlistening();
    return 0;
  }
}

異步客戶端套接字示例


下面的示例程序創(chuàng)建一個連接到服務(wù)器的客戶端。該客戶端是用異步套接字生成的,因此在等待服務(wù)器返回響應(yīng)時不掛起客戶端應(yīng)用程序的執(zhí)行。該應(yīng)用程序?qū)⒆址l(fā)送到服務(wù)器,然后在控制臺顯示該服務(wù)器返回的字符串。
 [c#]
using system;
using system.net;
using system.net.sockets;
using system.threading;
using system.text;
 
// state object for receiving data from remote device.
public class stateobject {
  public socket worksocket = null;              // client socket.
  public const int buffersize = 256;            // size of receive buffer.
  public byte[] buffer = new byte[buffersize];  // receive buffer.
  public stringbuilder sb = new stringbuilder();// received data string.
}
 
public class asynchronousclient {
  // the port number for the remote device.
  private const int port = 11000;
 
  // manualresetevent instances signal completion.
  private static manualresetevent connectdone = 
    new manualresetevent(false);
  private static manualresetevent senddone = 
    new manualresetevent(false);
  private static manualresetevent receivedone = 
    new manualresetevent(false);
 
  // the response from the remote device.
  private static string response = string.empty;
 
  private static void startclient() {
    // connect to a remote device.
    try {
      // establish the remote endpoint for the socket.
      // "host.contoso.com" is the name of the
      // remote device.
      iphostentry iphostinfo = dns.resolve("host.contoso.com");
      ipaddress ipaddress = iphostinfo.addresslist[0];
      ipendpoint remoteep = new ipendpoint(ipaddress, port);
 
      //  create a tcp/ip  socket.
      socket client = new socket(addressfamily.internetwork,
        sockettype.stream, protocoltype.tcp);
 
      // connect to the remote endpoint.
      client.beginconnect( remoteep, 
        new asynccallback(connectcallback), client);
      connectdone.waitone();
 
      // send test data to the remote device.
      send(client,"this is a test<eof>");
      senddone.waitone();
 
      // receive the response from the remote device.
      receive(client);
      receivedone.waitone();
 
      // write the response to the console.
      console.writeline("response received : {0}", response);
 
      // release the socket.
      client.shutdown(socketshutdown.both);
      client.close();
      
    } catch (exception e) {
      console.writeline(e.tostring());
    }
  }
 
  private static void connectcallback(iasyncresult ar) {
    try {
      // retrieve the socket from the state object.
      socket client = (socket) ar.asyncstate;
 
      // complete the connection.
      client.endconnect(ar);
 
      console.writeline("socket connected to {0}",
        client.remoteendpoint.tostring());
 
      // signal that the connection has been made.
      connectdone.set();
    } catch (exception e) {
      console.writeline(e.tostring());
    }
  }
 
  private static void receive(socket client) {
    try {
      // create the state object.
      stateobject state = new stateobject();
      state.worksocket = client;
 
      // begin receiving the data from the remote device.
      client.beginreceive( state.buffer, 0, stateobject.buffersize, 0,
        new asynccallback(receivecallback), state);
    } catch (exception e) {
      console.writeline(e.tostring());
    }
  }
 
  private static void receivecallback( iasyncresult ar ) {
    try {
      // retrieve the state object and the client socket 
      // from the async state object.
      stateobject state = (stateobject) ar.asyncstate;
      socket client = state.worksocket;
 
      // read data from the remote device.
      int bytesread = client.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));
 
        //  get the rest of the data.
        client.beginreceive(state.buffer,0,stateobject.buffersize,0,
          new asynccallback(receivecallback), state);
      } else {
        // all the data has arrived; put it in response.
        if (state.sb.length > 1) {
          response = state.sb.tostring();
        }
        // signal that all bytes have been received.
        receivedone.set();
      }
    } catch (exception e) {
      console.writeline(e.tostring());
    }
  }
 
  private static void send(socket client, 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.
    client.beginsend(bytedata, 0, bytedata.length, 0,
      new asynccallback(sendcallback), client);
  }
 
  private static void sendcallback(iasyncresult ar) {
    try {
      // retrieve the socket from the state object.
      socket client = (socket) ar.asyncstate;
 
      // complete sending the data to the remote device.
      int bytessent = client.endsend(ar);
      console.writeline("sent {0} bytes to server.", bytessent);
 
      // signal that all bytes have been sent.
      senddone.set();
    } catch (exception e) {
      console.writeline(e.tostring());
    }
  }
  
  public static int main(string[] args) {
    startclient();
    return 0;
  }
}





收集最實用的網(wǎng)頁特效代碼!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 岐山县| 五家渠市| 天门市| 唐河县| 都匀市| 理塘县| 通州区| 象山县| 梁平县| 肥城市| 天门市| 武穴市| 新昌县| 竹溪县| 苍梧县| 林州市| 衡山县| 项城市| 丰台区| 旺苍县| 太和县| 元氏县| 五寨县| 内黄县| 堆龙德庆县| 那曲县| 渭源县| 宁国市| 云和县| 鄂伦春自治旗| 舒兰市| 大同市| 定西市| 富民县| 太康县| 彝良县| 紫云| 三亚市| 克山县| 澄城县| 白银市|