出自:http://www.cnblogs.com/llllll/archive/2009/05/13/1455703.html
今天研究了一下c#的socket 异步通信,参考了上面地址的博客自己实践了一下,做了一下测试,少许的改动了一下,原文是可以完美运行的,我真是稍微改动按照自己的理解
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace socketAsyncCallback
{
public class StateObject
{
public Socket WorkSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
class Program
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
private static Socket listener;
static void Main(string[] args)
{
StartListening();
}
public static void StartListening()
{
byte[] bytes = new byte[1024];
IPAddress ipAddress = IPAddress.Parse("10.2.226.14");
int port = 8885;
IPEndPoint point = new IPEndPoint(ipAddress, port);
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(point);
listener.Listen(10);
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
//这里本来是在这里启动一个begin的,我把他挪到了AcceptCallback方法里,这样就不用让主线程等待了
/*
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting fo a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
allDone.WaitOne();
}
*/
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press Enter to continue");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
Console.WriteLine("come in AcceptCallback");
//allDone.Set();
Socket myListener = (Socket) ar.AsyncState;
Socket handler = myListener.EndAccept(ar);
//握手,因为我这里用来连接进来的client 是用的同步的,所以一定要握手才可以,我连接就是用的前面的一篇 socketClient的文章
handler.Send(Encoding.ASCII.GetBytes("server say hello"));
//这里是申创造一个容器, 来传递socket
StateObject state = new StateObject();
state.WorkSocket = handler;
handler.BeginReceive(state.buffer, 0, 1024, 0, new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
string content = string.Empty;
Console.WriteLine("READCALLBACK");
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.WorkSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
//Console.WriteLine(content);
if (content.IndexOf("<EOF>") > -1)
{
Console.WriteLine("Read {0} bytes from socket. \n Data: {1}",content.Length, content);
//给客户端响应,这里也可以注释掉,没有关系
Send(handler, content);
}
else
{
handler.BeginReceive(state.buffer, 0, 1024, 0, new AsyncCallback(ReadCallback),
state);
}
}
}
private static void Send(Socket handler, string data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket) ar.AsyncState;
int bytesSend = handler.EndSend(ar);
Console.WriteLine("Send {0} bytes to client.", bytesSend);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}