首页 > 编程 > .NET > 正文

使用.NET访问Internet(5) Paul_Ni(原作)

2024-07-10 13:04:54
字体:
来源:转载
供稿:网友

同步客户端套接字示例


下面的示例程序创建一个连接到服务器的客户端。该客户端是用同步套接字生成的,因此挂起客户端应用程序的执行,直到服务器返回响应为止。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。
 [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;
  }
}

同步服务器套接字示例


下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用同步套接字生成的,因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串“<eof>”,以发出表示消息结尾的信号。
 [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;
  }
}

异步客户端套接字示例


下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。
 [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;
  }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表