你运气好 using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading;// State object 从客户端异步的读取数据。 public class StateObject { // 客户端Socket public Socket workSocket = null; // 规定缓存的大小。 public const int BufferSize = 1024; // 申请缓存 public byte[] buffer = new byte[BufferSize]; // 已经接受的字符串。 public StringBuilder sb = new StringBuilder(); }public class AsynchronousSocketListener {
// 从客户端进来的字符串。 public static string data = null; // 线程信息。 public static ManualResetEvent allDone = new ManualResetEvent(false); public AsynchronousSocketListener() { } public static void StartListening() { // 申请缓存 byte[] bytes = new Byte[1024]; // 创建Socket的本地端。使用本地计算机的 DNS 名称。 IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); // 创建一个使用TCP协议的Socket Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); // 将 socket 邦定到本地端,并开始侦听。 try { listener.Bind(localEndPoint); listener.Listen(100); while (true) { // 设置线程为非终止状态。 allDone.Reset(); // 开始异步侦听。. Console.WriteLine("Waiting for a connection..."); listener.BeginAccept( new AsyncCallback(AcceptCallback),listener ); // 在下一个循环之前等待。直到有一个连接产生,进行下一次while循环。 allDone.WaitOne(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read();
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;// State object 从客户端异步的读取数据。
public class StateObject
{
// 客户端Socket
public Socket workSocket = null;
// 规定缓存的大小。
public const int BufferSize = 1024;
// 申请缓存
public byte[] buffer = new byte[BufferSize];
// 已经接受的字符串。
public StringBuilder sb = new StringBuilder();
}public class AsynchronousSocketListener
{
// 从客户端进来的字符串。
public static string data = null; // 线程信息。
public static ManualResetEvent allDone = new ManualResetEvent(false); public AsynchronousSocketListener()
{
} public static void StartListening()
{
// 申请缓存
byte[] bytes = new Byte[1024]; // 创建Socket的本地端。使用本地计算机的 DNS 名称。
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); // 创建一个使用TCP协议的Socket
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp ); // 将 socket 邦定到本地端,并开始侦听。
try
{
listener.Bind(localEndPoint);
listener.Listen(100); while (true)
{
// 设置线程为非终止状态。
allDone.Reset(); // 开始异步侦听。.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept( new AsyncCallback(AcceptCallback),listener ); // 在下一个循环之前等待。直到有一个连接产生,进行下一次while循环。
allDone.WaitOne();
} } catch (Exception e)
{
Console.WriteLine(e.ToString());
} Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
} public static void AcceptCallback(IAsyncResult ar)
{
// 产生让主线程继续运行的信号
allDone.Set(); // 获得有客户端连接的 socket
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar); // 创建 stateobject
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;
//从ar中 获得 stateobject 和套接字 handler
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket; // 从客户端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)); // 检查结束标记,如果没有则读更多的数据。
content = state.sb.ToString();
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, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
// 将字符串转化为 byte 类型的数据。
byte[] byteData = Encoding.ASCII.GetBytes(data); // 开始将数据传送到远程计算机。
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
} private static void SendCallback(IAsyncResult ar)
{
try
{
// 从 state object 中获得调用该函数的对象。
Socket handler = (Socket) ar.AsyncState; // 发送数据到远程计算机。
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.\n", bytesSent); //关闭Socket.
handler.Shutdown(SocketShutdown.Both);
handler.Close(); }
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Mained(String[] args)
{
StartListening();
return 0;
}
}--注意,如果没有结束soket的消息,socket会一直阻留内存.