使用.NET访问Internet(5) Paul

同步客户端套接字示例

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

 [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;
  }
}

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索c# remoting 多账套
, client
, data
, ane
, console
, remote
, socket client
, The
WriteLine
paul jaminet、无internet访问、无internet访问权限、无internet访问感叹号、网络无internet访问,以便于您获取更多的相关知识。

时间: 2024-08-18 03:34:15

使用.NET访问Internet(5) Paul的相关文章

使用.NET访问 Internet(1) Paul

Microsoft .NET 框架提供 Internet 服务的分层的.可扩展的和托管的实现,您可以将这些 Internet 服务快速而轻松地集成到您的应用程序中.您的应用程序可建立在可插接式协议的基础之上以便自动利用新的 Internet 协议,或者它们可以使用 Windows 套接字接口的托管实现来使用套接字级别上的网络. 介绍可插接式协议 Microsoft .NET 框架提供分层的.可扩展的和托管的 Internet 服务实现,您可以将它们快速而轻松地集成到您的应用程序中.System.

使用.NET访问 Internet(3) Paul

使用.NET访问 Internet(3) Paul_Ni(原作) 作者:中国资讯网 来源:zixuen.com 加入时间:2005-5-12 www.zixuen.com 使用 TCP 服务 TCPClient 类使用 TCP 从 Internet 资源请求数据.TcpClient 的方法和属性提取某个 Socket 实例的创建细节,该实例用于通过 TCP 请求和接收数据.由于到远程设备的连接表示为流,因此可以使用 .NET 框架流处理技术读取和写入数据.TCP 协议建立与远程终结点的连接,然后

使用.NET访问 Internet(2) Paul

实现异步请求 System.Net 类使用 .NET 框架的标准异步编程模型对 Internet 资源进行异步访问.WebRequest 类的 BeginGetResponse 和 EndGetResponse 方法分别启动和完成对 Internet 资源的异步请求.注意 在异步回调方法中使用同步调用可能会导致严重的性能降低.通过 WebRequest 及其子代实现的 Internet 请求必须使用 Stream.BeginRead 读取由 WebResponse.GetResponseStre

使用.NET访问Internet(4) Paul

使用异步客户端套接字 异步客户端套接字在等待网络操作完成时不挂起应用程序.相反,它使用标准 .NET 框架异步编程模型在一个线程上处理网络连接,而应用程序继续在原始线程上运行.异步套接字适用于大量使用网络或不能等待网络操作完成才能继续的应用程序.Socket 类遵循异步方法的 .NET 框架命名模式:例如,同步 Receive 方法对应异步 BeginReceive 和 EndReceive 方法.异步操作要求回调方法返回操作结果.如果应用程序不需要知道结果,则不需要任何回调方法.本节中的代码示

Android简明开发教程二十一:访问Internet 绘制在线地图

在例子Android简明开发教程十七:Dialog 显示图像 中我们留了一个例子DrawMap()没有实现,这个例子显示在线地图,目前大部分地图服务器都是将地图以图片存储以提高响应速 度. 一般大小为256X256个像素.具体可以参见离线地图下载方法解析. 比如: URL http://www.mapdigit.com/guidebeemap/maptile.php?type=MICROSOFTMAP&x=7&y=4&z=14 显示: 下面的例子访问Internet下载地图图片,并

您可能需要与该网络的internet服务提供商(isp)签署协议才能获得访问 internet的权限解决

 今天开机网络连接出现感叹号,但网络连接正常,点了疑难解答,提示"您可能需要与该网络的 internet 服务提供商(isp)签署协议才能获得访问 internet 的权限", 经过研究问题解决,现把方法共享下: 解决方案: 开始---运行----regedit. 打开后 1. 找到注册表键值HKEY_LOCAL_MACHINESYSTEMCurrentControlSetservicesNlaSvcParametersInternet 2. 双击HKEY_LOCAL_MACHINES

无线网络无法访问Internet

  无线网络连接正常,但是无法正常连接到Internet. 这样的情况可能是没有得到有效的IP地址,可以对无线网卡的地址进行检查.在一般情况下,无线网卡通过DHCP的方式获取IP地址和DNS服务器的地址.可以选择"开始"→"运行",然后输入cmd,单击"确定",就可以打开"命令提示符",再输入ipconfig/all,查看返回的结果.如果IP地址.网关和DNS都没有错误,却仍然无法访问Internet,就说明网关有问题. 检查

可以访问Internet无法访问其他电脑

  电脑在使用的时候可以正常访问Internet,也可以访问服务器,但是却无法访问其他电脑. 如果电脑在使用WINS解析,就有可能是由于WINS服务器的地址设置错误造成的.然后对网关的设置进行检查,如果双方属于不同的子网,网关的设置错误,则就不能看到其他工作站.还可以对子网掩码设置进行检查.

请教个问题,在VPC中,同一个subnet下,如何设置其它的instance通过同一个subnet下的某个NAT instance来访问internet?

问题描述 请教个问题,在VPC中,同一个subnet下,如何设置其它的instance通过同一个subnet下的某个NATinstance来访问internet? 解决方案 解决方案二:在VPC中有一个叫routetable的东西可用设置你想要的任何形式的路由.你只需要将subnet的route设置为从NATinstance走就可以了