异步服务器套接字示例

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这门语言为什么要起这个名字

    我只是一只可爱的小虫 前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:Liz喵 PS:如有需要Python学习资料的小 ...

  2. Sprint 5 summary: UI 界面更新,Azure端部署和用户反馈分析 12/28/2015

    本次sprint主要完成的任务有对手机APP的UI界面的更新,同时对Azure客户端的部署进行了相应的学习和有关的程序设计.同时对于ALPHA release的用户反馈做出相应的分析以确定接下来工作的 ...

  3. Daily Scrum 12/21/2015

    Process: Zhaoyang: Integrate the oxford Speech API Code to the IOS client and do some UI optimizatio ...

  4. CodeForces - 855B ring 前缀和

    邓布利多教授正在帮助哈利摧毁魂器.当他怀疑一个魂器出现在那里时,他去了冈特沙克.他看到Marvolo Gaunt的戒指,并将其确定为魂器.虽然他摧毁了它,但仍然受到诅咒的影响.斯内普教授正在帮助邓布利 ...

  5. python与excel的关系;铁打的python流水的excel

    现在很多行业,都离不开用Excel: 做财务的,要用Excel做报表:做物流的,会用Excel来跟踪订单情况:做HR的,会用Excel算工资:做分析的,会用Excel计算数据做报表.不知道你有没有这样 ...

  6. Os-hackNos-1靶机过关记录

    靶机地址:172.16.1.198(或112)  kali地址:172.16.1.108 1 信息收集 靶机界面如下 简单查看 OS:Ubuntu Web:Apache2.4.18 尝试端口扫描 开放 ...

  7. billu b0x2靶机渗透

    实战渗透靶机billu b0x2 攻击kali :192.168.41.147 靶机b0x2: 192.168.41.148 起手先nmap扫了一下 扫到了四个开放的端口,有ssh,http,rpcb ...

  8. Springboot:员工管理之查询员工列表(十(6))

    构建员工controller com\springboot\controller\EmployeeController.java package com.springboot.controller; ...

  9. 前端以BASE64码的形式上传图片

    前端以BASE64码的形式上传图片 一直有一个很苦恼的问题困扰着铁柱兄,每次上传图片的时候前端要写一大堆js,然后后台也要写一堆java代码做处理.于是就在想,有没有简单又方便的方法把图片上传.今天算 ...

  10. php 通过 yield 实现协程有什么使用场景

    来源:https://segmentfault.com/q/1010000010018151 参考:https://www.cnblogs.com/lynxcat/p/7954456.html 协程可 ...