我的代码在异步通信中必须要等Server端断掉后才能接收到数据,这是为什么?

uheart 2009-02-13 03:27:58
搞了半天 不知道怎么回事,Server端已经返回数据,但就是接收不到,非要等Server端断开后才能接收到 晕死了
SendCmd为前台ajax调用,Server能接收到我发送的命令.

[AjaxPro.AjaxMethod]
public string SendCmd(string cmd)
{
string str = "";

try
{
// string strCmdPar = "a=1;b=2;";
string strCmdPar = cmd;
PacketObj pk = new PacketObj();
char[] chrCmd = strCmdPar.ToCharArray();
ArrayList alCmdPar = new ArrayList();

foreach(char chr in chrCmd)
{
byte byt = (byte)chr;
byte[] byts = pk.CmdEscape(new byte[1]{byt});
foreach(byte bytTmp in byts)
{
alCmdPar.Add(bytTmp);
// alCmdPar.Add(byt);
}
}

byte[] arrPar = new byte[alCmdPar.Count];
for(int j = 0 ; j < alCmdPar.Count ; j++)
{
arrPar[j] = (byte)alCmdPar[j];
}

byte[] bytData = this.GetCmdPacket(arrPar);
str = SendCommand(bytData);
}
catch(Exception ce)
{
str=ce.Message;
}

return str;
}

#region
// The port number for the remote device.
private const int port = 6205;
private const string ServerIp = "192.168.2.100";

// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static ManualResetEvent receiveDone = new ManualResetEvent(false);

// The response from the remote device.
private static String response = String.Empty;
public static PacketObj pc = new PacketObj();



public byte[] GetCmdPacket(byte[] cmdPar)
{

byte[] bytCmd = new byte[4096];
byte bytStatus = 0x10 | 0xe0;
byte[] ClientID = new byte[]{0x31,0x31,0x30,0x31};
byte[] SiteID = new byte[]{0x61,0x31,0x30,0x31};
byte ProtocolCommand = 0x07;

bytCmd = pc.MergerPacket(bytStatus,ClientID,SiteID,ProtocolCommand,cmdPar);

return bytCmd;

}




private string SendCommand(byte[] byteData)
{
try
{



IPAddress ip = IPAddress.Parse(ServerIp);
IPEndPoint remoteEP = new IPEndPoint(ip, port);

Socket client = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

client.BeginConnect( remoteEP,new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();

Send(client,byteData);
sendDone.WaitOne();

Receive(client);
receiveDone.WaitOne();

// Console.WriteLine("Response received : {0}", response);

client.Shutdown(SocketShutdown.Both);
client.Close();


}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return response;
}




private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket) ar.AsyncState;

client.EndConnect(ar);

// Console.WriteLine("Socket connected to {0}",client.RemoteEndPoint.ToString());

connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

private static void Send(Socket client, byte[] byteData)
{
client.BeginSend(byteData,0,pc.PacketLen,0,new AsyncCallback(SendCallback),client);
}

private static void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket) ar.AsyncState;

int bytesSent = client.EndSend(ar);
// Console.WriteLine("Sent {0} bytes to server.", bytesSent);

sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}


private void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocket = client;

client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

private void ReceiveCallback( IAsyncResult ar )
{
try
{
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;

int bytesRead = client.EndReceive(ar);

if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}



public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
#endregion

...全文
76 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
fskang 2009-02-14
  • 打赏
  • 举报
回复
你查下你的服务端代码吧。还有你的客户端代码用了那么多waithandle,你的异步调用还有什么意义呢?
uheart 2009-02-13
  • 打赏
  • 举报
回复
我再把代码整理一下 上面的太乱了

[AjaxPro.AjaxMethod]
public string SendCmd(string cmd)
{
string str = "";

try
{

byte[] bytData = this.GetCmdPacket(cmd);
str = SendCommand(bytData);
}
catch(Exception ce)
{
str=ce.Message;
}
return str;
}



private const int port = 6205;
private const string ServerIp = "192.168.2.100";


private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static ManualResetEvent receiveDone = new ManualResetEvent(false);

private static String response = String.Empty;
public static PacketObj pc = new PacketObj();



public byte[] GetCmdPacket(byte[] cmdPar)
{

byte[] bytCmd = new byte[4096];
byte bytStatus = 0x10 | 0xe0;
byte[] ClientID = new byte[]{0x31,0x31,0x30,0x31};
byte[] SiteID = new byte[]{0x61,0x31,0x30,0x31};
byte ProtocolCommand = 0x07;

bytCmd = pc.MergerPacket(bytStatus,ClientID,SiteID,ProtocolCommand,cmdPar);

return bytCmd;
}




private string SendCommand(byte[] byteData)
{
try
{
IPAddress ip = IPAddress.Parse(ServerIp);
IPEndPoint remoteEP = new IPEndPoint(ip, port);
Socket client = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect( remoteEP,new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();

Send(client,byteData);
sendDone.WaitOne();

Receive(client);
receiveDone.WaitOne();
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return response;
}

private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket) ar.AsyncState;
client.EndConnect(ar);
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

private static void Send(Socket client, byte[] byteData)
{
client.BeginSend(byteData,0,pc.PacketLen,0,new AsyncCallback(SendCallback),client);
}

private static void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket) ar.AsyncState;
int bytesSent = client.EndSend(ar);
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

private void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

private void ReceiveCallback( IAsyncResult ar )
{
try
{
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}


lyymax 2009-02-13
  • 打赏
  • 举报
回复
看代码看的眼睛都花了。。。

你是不是用了BufferStream了?
建议一次通讯后用flush方法确定把字符串都发出去。
wuyi8808 2009-02-13
  • 打赏
  • 举报
回复
up

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧