日期:2014-05-17 浏览次数:21334 次
public static ManualResetEvent allDone = new ManualResetEvent(false);
private Thread yth;
private bool listenerRun = true;
Socket listener;
private const int maxsocket = 10000;
int port = 54321;
private void buttonStart_Click(object sender, EventArgs e)
{
listenerRun = true;
yth = new Thread(new ThreadStart(ListenClient));
yth.IsBackground = true;
yth.Start();
this.buttonStart.Enabled = false;
this.buttonStop.Enabled = true;
}
public void ListenClient()
{
while (listenerRun)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallBack), listener);
allDone.WaitOne();
}
}
private void AcceptCallBack(IAsyncResult ar)
{
try
{
allDone.Set();
Socket sok = (Socket)ar.AsyncState;
Socket client = sok.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = client;
if(client.Available>0)
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallBack), state);
&