iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >C#中怎么实现异步套接字
  • 550
分享到

C#中怎么实现异步套接字

2023-06-17 23:06:09 550人浏览 泡泡鱼
摘要

今天就跟大家聊聊有关C#中怎么实现异步套接字,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。下面的C#异步套接字实现实例程序创建一个连接到服务器的客户端。该客户端是用C#异步套接字生成

今天就跟大家聊聊有关C#中怎么实现异步套接字,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

下面的C#异步套接字实现实例程序创建一个连接到服务器的客户端。该客户端是用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 {       // Client socket.       public Socket workSocket = null;       // Size of receive buffer.       public const int BufferSize = 256;       // Receive buffer.       public byte[] buffer = new byte[BufferSize];       // Received data string.       public StringBuilder sb = new StringBuilder();       }       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.       // 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, 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 asynchronous 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#异步套接字在服务器的示例 下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用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 {       // Client socket.       public Socket workSocket = null;       // Size of receive buffer.       public const int BufferSize = 1024;       // Receive buffer.       public byte[] buffer = new byte[BufferSize];       // Received data string.       public StringBuilder sb = new StringBuilder();       }       public class AsynchronousSocketListener {       // 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("\nPress 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 asynchronous 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;       }       }

看完上述内容,你们对C#中怎么实现异步套接字有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网精选频道,感谢大家的支持。

--结束END--

本文标题: C#中怎么实现异步套接字

本文链接: https://www.lsjlt.com/news/294235.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C#中怎么实现异步套接字
    今天就跟大家聊聊有关C#中怎么实现异步套接字,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。下面的C#异步套接字实现实例程序创建一个连接到服务器的客户端。该客户端是用C#异步套接字生成...
    99+
    2023-06-17
  • C#中如何实现异步套接字
    这篇文章将为大家详细讲解有关C#中如何实现异步套接字,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。创建一个连接到服务器的客户端。该客户端是用C#异步套接字生成的,因此在等待服务器返回响应时不...
    99+
    2023-06-17
  • .NET编程——利用C#实现TCP协议的异步通信Socket套接字(WinForm)
    本文将介绍利用基于TCP通信协议的Socket实现服务器与客户端之间的数据传输。 目录 前言 计算机通信 创建服务器 服务器通信 创建客户端 客户端通信 前言         TCP/IP(Transmission Control Pr...
    99+
    2023-09-04
    tcp/ip c# mysql 服务器
  • C#实现套接字发送接收数据
    本文实例为大家分享了C#实现套接字发送接收数据的具体代码,供大家参考,具体内容如下 服务端 namespace TestServer { public partial ...
    99+
    2024-04-02
  • C++中怎么实现异步操作
    C++中怎么实现异步操作,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。实现(代码)#include <iostream> #include&nb...
    99+
    2023-06-17
  • C#中怎么实现异步调用
    C#中怎么实现异步调用,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。首先,C#异步调用出来的新线程,必须回收,不回收是浪费资源的可耻行为,.NET也是不允许的,所以你别想钻...
    99+
    2023-06-17
  • C#中怎么实现异步操作
    C#中怎么实现异步操作,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。//首先准备好,要进行异步的方法(能异步的,***不多线程)  private ...
    99+
    2023-06-17
  • C#中怎么实现长异步操作
    本篇文章为大家展示了C#中怎么实现长异步操作,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。程序中执行按钮的Click 处理如下:private void _btnRun_Clic...
    99+
    2023-06-18
  • C#多线程实现异步接口
    异步接口的声明 我们已经了解到,如果一个方法是异步的,那么这个方法的返回值类型是Task<T>,那么接口中该如何规定异步方法呢? 一样的,如果接口中的方法是异步的,那么规...
    99+
    2024-04-02
  • C#如何实现套接字发送接收数据
    这篇文章主要介绍了C#如何实现套接字发送接收数据,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。具体内容如下服务端namespace TestServer{ ...
    99+
    2023-06-21
  • C#中怎么实现异步网络编程
    这期内容当中小编将会给大家带来有关C#中怎么实现异步网络编程,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。C#异步网络编程两大方法一、Asynchronous Sockets的方法Socket类的很多连接...
    99+
    2023-06-17
  • C#中怎么实现一个异步传输字符串客户端
    这篇文章给大家介绍C#中怎么实现一个异步传输字符串客户端,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。C#异步传输字符串客户端的实现与服务端类似,我们首先对TcpClient进行一个简单的包装,使它的使用更加方便一些,...
    99+
    2023-06-17
  • C#中怎么实现同步调用和异步调用
    今天就跟大家聊聊有关C#中怎么实现同步调用和异步调用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。C#委托的Invoke方法用来进行同步调用。同步调用也可以叫阻塞调用,它将阻塞当前线...
    99+
    2023-06-17
  • python实现套接字创建
    目录1、网络协议  2、地址族  3、通过域名获取IP地址4、socket1、网络协议   TCP / IP 是设备用于在 Internet 和大多数本地网络上进行通信的一组协议。 ...
    99+
    2024-04-02
  • C#中怎么利用Socket实现异步通讯
    这篇文章将为大家详细讲解有关C#中怎么利用Socket实现异步通讯,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。C# Socket异步通讯客户端之主程序:using System;using...
    99+
    2023-06-17
  • C#中怎么利用AsyncResult实现异步编程
    这篇文章给大家介绍C#中怎么利用AsyncResult实现异步编程,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。C#异步编程模式IAsyncResult概述IAsyncResult 异步设计模式通过名为 BeginOp...
    99+
    2023-06-17
  • ajax中怎么实现同步异步
    ajax中怎么实现同步异步,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。$("#btn_saveFWSB"...
    99+
    2024-04-02
  • C++怎么实现异步数据交换
    本篇内容介绍了“C++怎么实现异步数据交换”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!异步数据交换,除了阻塞函数 send() 和 rec...
    99+
    2023-07-04
  • C#中怎么利用委托实现异步调用
    这篇文章将为大家详细讲解有关C#中怎么利用委托实现异步调用,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。委托实现C#异步调用的步骤:定义委托。将要进行异步调用的方法“实例化”到定义的委托。在...
    99+
    2023-06-17
  • Python中怎么实现同步和异步
    Python中怎么实现同步和异步,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。一、同步与异步#同步编程(同一时间只能做一件事,做完了才能做下一件事情) ...
    99+
    2023-06-17
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作