服务端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
//
/* 同步与异步小知识
*
* 所谓同步,可以理解为在执行完一个函数或方法之后,
* 一直等待系统返回值或消息,这时程序是出于阻塞的,
* 只有接收到返回的值或消息后才往下执行其他的命令。
* 所谓异步,执行完函数或方法后,不必阻塞性地等待返回值或消息,
* 只需要向系统委托一个异步过程,那么当系统接收到返回值或消息时,
* 系统会自动触发委托的异步过程,从而完成一个完整的流程。
*/
//
//
//
// 异步socket例子------服务器端。
// 2009-11-27
//
//
//细致、深刻、耐心的理解这种处理的机制。以便以后可以熟练的应用到项目中去。
namespace AsyncSocketServer
{
// 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()
{
}
/// <summary>
/// 开始监听
/// </summary>
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());