微软C#套接字异步通信代码

2024-09-07 11:48

本文主要是介绍微软C#套接字异步通信代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Asynchronous Server Socket Example.NET Framework 4 其他版本 
The following example program creates a server that receives connection requests from clients. The server is built with an asynchronous socket, so execution of the server application is not suspended while it waits for a connection from a client. The application receives a string from the client, displays the string on the console, and then echoes the string back to the client. The string from the client must contain the string "<EOF>" to signal the end of the message.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;}
}//======================================================================
Asynchronous Client Socket Example.NET Framework 4 其他版本 
The following example program creates a client that connects to a server. The client is built with an asynchronous socket, so execution of the client application is not suspended while the server returns a response. The application sends a string to the server and then displays the string returned by the server on the console.客户端程序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#套接字异步通信代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1144981

相关文章

使用Python实现一个优雅的异步定时器

《使用Python实现一个优雅的异步定时器》在Python中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

C#实现将Excel表格转换为图片(JPG/ PNG)

《C#实现将Excel表格转换为图片(JPG/PNG)》Excel表格可能会因为不同设备或字体缺失等问题,导致格式错乱或数据显示异常,转换为图片后,能确保数据的排版等保持一致,下面我们看看如何使用C... 目录通过C# 转换Excel工作表到图片通过C# 转换指定单元格区域到图片知识扩展C# 将 Excel

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

C++使用printf语句实现进制转换的示例代码

《C++使用printf语句实现进制转换的示例代码》在C语言中,printf函数可以直接实现部分进制转换功能,通过格式说明符(formatspecifier)快速输出不同进制的数值,下面给大家分享C+... 目录一、printf 原生支持的进制转换1. 十进制、八进制、十六进制转换2. 显示进制前缀3. 指

C#中async await异步关键字用法和异步的底层原理全解析

《C#中asyncawait异步关键字用法和异步的底层原理全解析》:本文主要介绍C#中asyncawait异步关键字用法和异步的底层原理全解析,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录C#异步编程一、异步编程基础二、异步方法的工作原理三、代码示例四、编译后的底层实现五、总结C#异步编程

C#TextBox设置提示文本方式(SetHintText)

《C#TextBox设置提示文本方式(SetHintText)》:本文主要介绍C#TextBox设置提示文本方式(SetHintText),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录C#TextBox设置提示文本效果展示核心代码总结C#TextBox设置提示文本效果展示核心代

C#中DrawCurve的用法小结

《C#中DrawCurve的用法小结》本文主要介绍了C#中DrawCurve的用法小结,通常用于绘制一条平滑的曲线通过一系列给定的点,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 如何使用 DrawCurve 方法(不带弯曲程度)2. 如何使用 DrawCurve 方法(带弯曲程度)3.使用Dr

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

jupyter代码块没有运行图标的解决方案

《jupyter代码块没有运行图标的解决方案》:本文主要介绍jupyter代码块没有运行图标的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录jupyter代码块没有运行图标的解决1.找到Jupyter notebook的系统配置文件2.这时候一般会搜索到