微软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

相关文章

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

poj 1258 Agri-Net(最小生成树模板代码)

感觉用这题来当模板更适合。 题意就是给你邻接矩阵求最小生成树啦。~ prim代码:效率很高。172k...0ms。 #include<stdio.h>#include<algorithm>using namespace std;const int MaxN = 101;const int INF = 0x3f3f3f3f;int g[MaxN][MaxN];int n

系统架构师考试学习笔记第三篇——架构设计高级知识(20)通信系统架构设计理论与实践

本章知识考点:         第20课时主要学习通信系统架构设计的理论和工作中的实践。根据新版考试大纲,本课时知识点会涉及案例分析题(25分),而在历年考试中,案例题对该部分内容的考查并不多,虽在综合知识选择题目中经常考查,但分值也不高。本课时内容侧重于对知识点的记忆和理解,按照以往的出题规律,通信系统架构设计基础知识点多来源于教材内的基础网络设备、网络架构和教材外最新时事热点技术。本课时知识

用命令行的方式启动.netcore webapi

用命令行的方式启动.netcore web项目 进入指定的项目文件夹,比如我发布后的代码放在下面文件夹中 在此地址栏中输入“cmd”,打开命令提示符,进入到发布代码目录 命令行启动.netcore项目的命令为:  dotnet 项目启动文件.dll --urls="http://*:对外端口" --ip="本机ip" --port=项目内部端口 例: dotnet Imagine.M

计算机毕业设计 大学志愿填报系统 Java+SpringBoot+Vue 前后端分离 文档报告 代码讲解 安装调试

🍊作者:计算机编程-吉哥 🍊简介:专业从事JavaWeb程序开发,微信小程序开发,定制化项目、 源码、代码讲解、文档撰写、ppt制作。做自己喜欢的事,生活就是快乐的。 🍊心愿:点赞 👍 收藏 ⭐评论 📝 🍅 文末获取源码联系 👇🏻 精彩专栏推荐订阅 👇🏻 不然下次找不到哟~Java毕业设计项目~热门选题推荐《1000套》 目录 1.技术选型 2.开发工具 3.功能

【STM32】SPI通信-软件与硬件读写SPI

SPI通信-软件与硬件读写SPI 软件SPI一、SPI通信协议1、SPI通信2、硬件电路3、移位示意图4、SPI时序基本单元(1)开始通信和结束通信(2)模式0---用的最多(3)模式1(4)模式2(5)模式3 5、SPI时序(1)写使能(2)指定地址写(3)指定地址读 二、W25Q64模块介绍1、W25Q64简介2、硬件电路3、W25Q64框图4、Flash操作注意事项软件SPI读写W2

代码随想录冲冲冲 Day39 动态规划Part7

198. 打家劫舍 dp数组的意义是在第i位的时候偷的最大钱数是多少 如果nums的size为0 总价值当然就是0 如果nums的size为1 总价值是nums[0] 遍历顺序就是从小到大遍历 之后是递推公式 对于dp[i]的最大价值来说有两种可能 1.偷第i个 那么最大价值就是dp[i-2]+nums[i] 2.不偷第i个 那么价值就是dp[i-1] 之后取这两个的最大值就是d

pip-tools:打造可重复、可控的 Python 开发环境,解决依赖关系,让代码更稳定

在 Python 开发中,管理依赖关系是一项繁琐且容易出错的任务。手动更新依赖版本、处理冲突、确保一致性等等,都可能让开发者感到头疼。而 pip-tools 为开发者提供了一套稳定可靠的解决方案。 什么是 pip-tools? pip-tools 是一组命令行工具,旨在简化 Python 依赖关系的管理,确保项目环境的稳定性和可重复性。它主要包含两个核心工具:pip-compile 和 pip