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

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

典型的异步服务器端套接字构建相关推荐

  1. 典型的异步客户端套接字构建

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

  2. 典型的同步客户端、服务器端套接字的创建

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

  3. 【Groovy】使用 Groovy 语言开发服务器 Server 和客户端 Client 套接字程序 ( 服务器端开发 )

    文章目录 一.服务器端 ServerSocket 开发 1.创建服务器端套接字 ServerSocket 2.等待客户端请求 3.管理客户端连接 4.接收客户端数据线程 5.向客户端发送数据线程 二. ...

  4. 基于TCP/IP的套接字服务器端和客户端编程

    (本文章内容来源于网络,仅供学习之用,别无二心,希望不要有纠纷,谢谢!) 基于 TCP 的套接字编程的所有客户端和服务器端都是从调用socket 开始,它返回一个套接字描述符.客户端随后调用conne ...

  5. Python网络编程2:创建套接字和套接字对象的内建方法

    1.使用socket模块中socket()函数创建套接字: socket()函数返回一个socket对象,该对象的方法实现了各种socket系统调用. 语法: import socket socket ...

  6. 安卓学习笔记40:基于套接字网络编程

    文章目录 零.学习目标 一.Socket概述 (一)两种传输模式 (二)基于Socket网络编程 三.案例演示 - C/S架构聊天室 (一)运行效果 (二)涉及知识点 (三)实现步骤 1.创建聊天服务 ...

  7. think in java 读书笔记 2 —— 套接字

    目录 think in java 读书笔记 1 --移位 think in java 读书笔记 2 -- 套接字 think in java 读书笔记 3 -- 数据报 概要 1. 套接字基本知识 2 ...

  8. 什么是Python中的套接字编程?

    摘要:本文涵盖了有关使用Python进行套接字编程的所有领域.套接字可以帮助您建立这些连接,而Python无疑可以简化连接. 本文分享自华为云社区<从零开始学python | 什么是Python ...

  9. TCP/IP网络编程:P1->理解网络编程和套接字

    本系列文章为<TCP/IP网络编程----尹圣雨>学习笔记 文章目录 一.理解网络编程和套接字 1.1 构建接电话套接字 1.2 编写"Hello world!"服务器 ...

最新文章

  1. SpringBoot+SpringSecurity前后端分离+Jwt的权限认证(改造记录)
  2. com:向对象到面向服务
  3. boost::callable_traits添加volatile成员的测试程序
  4. 超级计算机阿波罗11,Apollo 8000推进超算科学发展
  5. 2019 秋招提前批蘑菇街一面面经(带答案)
  6. c语言c 的区别,C语言与C++的区别
  7. 百位云计算专家齐聚湖畔大学,阿里云MVP全球闭门会聚焦数字化转型
  8. 软件工程-团队作业3
  9. SQL SERVER BCP的用法
  10. MySQL数据库之分库分表方案
  11. 使用canvas给页面添加文字水印
  12. Spring MVC 学习笔记 by starscream
  13. JWT令牌生成与校验
  14. linux文件夹可视化工具,4款简单实用的的服务器文件管理工具推荐
  15. 腾讯云神笔低代码平台的申请没通过,只能等公测了
  16. jQuery功能简述
  17. win7出winsock问题了!~~~~~
  18. 阿蒙森 斯科特_斯科特的单元测试定律
  19. 保存PictureBox绘制的图像
  20. windows bat

热门文章

  1. 如何聊才能突出自己软实力,打动面试官
  2. 【hyddd驱动开发学习】DDK与WDK
  3. UnityShader中的Queue
  4. LeetCode问题7
  5. express下使用ES6
  6. PHP利用memcache缓存技术提高响应速度
  7. ulimit命令学习
  8. php表格打印输出,PHP输出表格
  9. 2.JAVA基础——数据类型、变量及运算符
  10. VB 中定义FileSystemObject对象,要先添加对象