异步服务器套接字示例

From https://msdn.microsoft.com/zh-cn/library/fx6588te(v=vs.110).aspx

下面的示例程序创建接收来自客户端的连接请求的服务器。 服务器以异步套接字生成,因此,服务器应用程序的执行不会挂起,它在等待从客户端时的连接。 应用程序收到来自客户端的字符串,在控制台上显示字符串,然后回显该字符串返回给客户端。 从客户端的字符串必须包含字符串“”用于通知消息的结尾。

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

DotNet:Socket Server 异步套接字服务端实现的更多相关文章

  1. 通过开启子进程的方式实现套接字服务端可以并发的处理多个链接以及通讯循环(用到了subprocess模块,解决粘包问题)

    今日作业:通过开启子进程的方式实现套接字服务端可以并发的处理多个链接以及通讯循环(用到了subprocess模块,解决粘包问题) server(服务端) import socket from mult ...

  2. 5-tcp套接字服务端编程

    import socket 1.创建套接字 sockfd= socket.socket(socket_family = AF_INIT,socket_type=SOCK_STREAM,proto) 功 ...

  3. TCP下的套接字服务端实现并发 作业题

    # 服务端 import socket from threading import Thread """ 服务端 1.要有固定的IP和PORT 2.24小时不间断提供服务 ...

  4. c++ 网络编程(七) LINUX下 socket编程 基于套接字的标准I/O函数使用 与 fopen,feof,fgets,fputs函数用法

    原文作者:aircraft 原文链接:https://www.cnblogs.com/DOMLX/p/9614820.html 一.标准I/O 1,什么是标准I/O?其实是指C语言里的文件操作函数,如 ...

  5. Python套接字编程(1)——socket模块与套接字编程

    在Python网络编程系列,我们主要学习以下内容: 1. socket模块与基本套接字编程 2. socket模块的其他网络编程功能 3. SocketServer模块与简单并发服务器 4. 异步编程 ...

  6. nodejs 实现套接字服务

    nodejs实现套接字服务     一 什么是套接字 1.套接字允许一个进程他通过一个IP地址和端口与另一个进程通信,当你实现对运行在同一台服务器上的两个不同进程的进程间通信或访问一个完全不同的服务器 ...

  7. socket()模块和套接字对象的内建方法

    一.socket()模块函数 要使用socket.socket()函数来创建套接字,其语法如下: socket(socket_family,socket_type,protocol=0) 如上所述,s ...

  8. 【转】 VC中TCP实现 异步套接字编程的原理+代码

    所谓的异步套接字编程就是  调用了 如下函数   WSAAsyncSelect   设置了 套接字的状态为异步,有关函数我会在下面详细介绍... 异步套接字解决了 套接字编程过程中的堵塞问题 .... ...

  9. socket模块(套接字模块)

    socket模块(套接字模块) 一.最简单版本(互传一次就结束) # 客户端 import socket client = socket.socket() client.connect(('127.0 ...

随机推荐

  1. 用Python画的,5 种非传统的可视化技术,超炫酷的动态图

    数据可以帮助我们描述这个世界.阐释自己的想法和展示自己的成果,但如果只有单调乏味的文本和数字,我们却往往能难抓住观众的眼球.而很多时候,一张漂亮的可视化图表就足以胜过千言万语.本文将介绍 5 种基于 ...

  2. PHP函数:php_sapi_name

    php_sapi_name()  - 返回 web 服务器和 PHP 之间的接口类型. SAPI(Server Application Programming Interface)服务器应用程序编程接 ...

  3. 基于 HTML5 WebGL 的高炉炼铁厂可视化系统

    前言       在当今 工业4.0 新时代的推动下,不仅迎来了 工业互联网 的发展,还开启了 5G 时代的新次元.而伴随着带宽的提升,网络信息飞速发展,能源管控上与实时预警在工业互联网中也占着举足轻 ...

  4. 5. react父子组件

    1. 父组件如何获取子组件的方法以及属性? 1.)父组件: render( ){ console.log( this.refs.getmethod ): return ( <div> &l ...

  5. python实现线性回归之简单回归

    代码来源:https://github.com/eriklindernoren/ML-From-Scratch 首先定义一个基本的回归类,作为各种回归方法的基类: class Regression(o ...

  6. php原生函数应用

    php常见基本的函数 一.字符串函数 implode — 将一个一维数组的值转化为字符串 lcfirst — 使一个字符串的第一个字符小写 ltrim — 删除字符串开头的空白字符(或其他字符) rt ...

  7. centos 服务器上部署 xxl-job 通过 feign 访问 eureka 上注册的 service timeout

    部署方式 1.使用 jar 包部署 出现的问题 1.通过 feign 调用其他服务,出现超时的问题,该问题不是 ribbon.hystrix 没有配置导致的超时,经过测试,即使配置了也没有作用,该方法 ...

  8. centos7安装及部署zabbix监控

    一:实验环境 server.zabbix.com-------------------- 192.168.200.11 agent.zabbix.com------------------------ ...

  9. 【Linux常见命令】cp命令

    cp - copy files and directories 拷贝文件或目标文件夹,默认不能直接拷贝目录,通过-r参数设置递归复制目录 copy 语法: cp [OPTION]... [-T] SO ...

  10. ajax 技术

    ajax 技术 $.ajax({ url:"", type:'GET', success:function(data){ console.log(data); }, error:f ...