socket服务端 异步通信
源代码如下:
客户端接入的时候,
单步调试能进入while(true),步进到reset,但是却不调用listenOK那个回调方法
求助
namespace d_webListener
{
public class d_webListener
{
private Thread serverRun;
private String ip = "";
private System.Windows.Forms.Label l1;
private int port = 0;
private Socket server;
private Socket client;
private byte[] bytes = new byte[1024]; //接收包头专用
//private byte[] scToByte; //将结构转化为byte
private conCom.conCom cc1;
private d_windows.d_windows dWindows;
private xmlMem.xmlMem xm = new xmlMem.xmlMem();
public static ManualResetEvent allDone = new ManualResetEvent(false);
delegate void sendToUp(string s);
sendToUp stu;
private void sendToAgent(string s)
{
StreamWriter sw = new StreamWriter(".\\out.txt",true);
sw.Write(s);
sw.Flush();
sw.Close();
s = s.Insert(s.IndexOf("HTTP/1.1") - 1, "\r\n");
xm.createFileInMem();
xm.addNodeInMem("FUND_ACCOUNT", "102045459");
xm.addNodeInMem("HTTP_REQ", s);
cc1.creatStruct(xm.doc().Length, xm.doc().Length, 400, 'M', 0);
cc1.SendData();
cc1.SendBody(xm.doc());
}
public d_webListener(System.Windows.Forms.Label l1,conCom.conCom cc1)
{
serverRun = new Thread(threadRun);
this.l1 = l1;
this.cc1 = cc1;
}
public String IP
{
set { ip = value; }
get { return ip; }
}
public int PORT
{
set { port = value; }
get { return port; }
}
public void connect()
{
try
{
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, this.port);
this.server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(localEndPoint);
server.Listen(10);
serverRun.Start();
}
catch (Exception ee)
{
}
}
private void ListenOK(IAsyncResult ar)
{
try
{
// 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);
handler.BeginReceive(bytes, 0, 1024, SocketFlags.None, new AsyncCallback(RecData), client);
}
catch (Exception e)
{
//
}
}
private void RecData(IAsyncResult ar)
{
try
{
stu = new sendToUp(sendToAgent);
xm.xmlInit();
Socket handle = (Socket)ar.AsyncState;
int length = handle.EndReceive(ar);
l1.Invoke(stu, Encoding.Default.GetString(bytes, 0, length));
handle.BeginReceive(bytes, 0, 1024, SocketFlags.None, new AsyncCallback(RecData), handle);
}
catch (Exception ee)
{
}
}
private void threadRun()
{
try
{
while (true)
{
//Set the event to nonsignaled state.设置无信号状态的事件
allDone.Reset();
//Start an asynchronous socket to listen for connections.重新 启动异步连接
server.BeginAccept(new AsyncCallback(ListenOK), server);
//Wait until a connection is made before continuing.等待连接创建后继续
allDone.WaitOne();
}
}
catch (Exception e)
{
//
}
}
}
}