Socket,里的OnReceive(int) 问题

qnetg123 2012-03-05 05:41:29
当我程序中某个地方进行一个
while(1)
{
if (bool)
break;
}
的时间等待时,OnReceive也要等这个循环跳出为止,这是为什么呢,有什么方法解决
...全文
82 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Kevin_Perkins 2012-03-06
  • 打赏
  • 举报
回复
我觉得很有可能与CriticalSection有关系。你给的代码不全,不知道你的那个循环是怎么写的。线程之间互斥了。
赵4老师 2012-03-06
  • 打赏
  • 举报
回复
仅供参考
//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <process.h>
#include <io.h>
//Log{
#define MAXLOGSIZE 10000000
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
char logstr[16000];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
void Lock(CRITICAL_SECTION *l) {
EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
LeaveCriticalSection(l);
}
void LogV(const char *pszFmt,va_list argp) {
struct tm *now;
struct timeb tb;

if (NULL==pszFmt||0==pszFmt[0]) return;
if (-1==_vsnprintf(logstr,ARRSIZE(logstr),pszFmt,argp)) logstr[ARRSIZE(logstr)-1]=0;
ftime(&tb);
now=localtime(&tb.time);
sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
sprintf(timestr,"%02d:%02d:%02d",now->tm_hour ,now->tm_min ,now->tm_sec );
sprintf(mss,"%03d",tb.millitm);
printf("%s %s.%s %s",datestr,timestr,mss,logstr);
flog=fopen(logfilename1,"a");
if (NULL!=flog) {
fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
if (ftell(flog)>MAXLOGSIZE) {
fclose(flog);
if (rename(logfilename1,logfilename2)) {
remove(logfilename2);
rename(logfilename1,logfilename2);
}
flog=fopen(logfilename1,"a");
if (NULL==flog) return;
}
fclose(flog);
}
}
void Log(const char *pszFmt,...) {
va_list argp;

Lock(&cs_log);
va_start(argp,pszFmt);
LogV(pszFmt,argp);
va_end(argp);
Unlock(&cs_log);
}
//Log}
#define ASIZE 200
#define BSIZE 240
#define CSIZE 2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX ;
CRITICAL_SECTION cs_BBB ;
struct FIFO_BUFFER {
int head;
int tail;
int size;
char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
int i,j,k;
char binstr[80];

Lock(&cs_HEX);
for (i=0;i<len;i++) {
if (0==(i%16)) {
sprintf(binstr,"%03d %04x -",cn,i);
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
} else if (15==(i%16)) {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
sprintf(binstr,"%s ",binstr);
for (j=i-15;j<=i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
} else {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
}
}
if (0!=(i%16)) {
k=16-(i%16);
for (j=0;j<k;j++) {
sprintf(binstr,"%s ",binstr);
}
sprintf(binstr,"%s ",binstr);
k=16-k;
for (j=i-k;j<i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
}
Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;

lent=0;
Lock(cs);
if (fbuf->size>=len) {
lent=len;
if (fbuf->head+lent>BSIZE) {
len1=BSIZE-fbuf->head;
memcpy(buf ,fbuf->data+fbuf->head,len1);
len2=lent-len1;
memcpy(buf+len1,fbuf->data ,len2);
fbuf->head=len2;
} else {
memcpy(buf ,fbuf->data+fbuf->head,lent);
fbuf->head+=lent;
}
fbuf->size-=lent;
}
Unlock(cs);
return lent;
}
void thdB(void *pcn) {
char *recv_buf;
int recv_nbytes;
int cn;
int wc;
int pb;

cn=(int)pcn;
Log("%03d thdB thread begin...\n",cn);
while (1) {
Sleep(10);
recv_buf=(char *)Cbuf;
recv_nbytes=CSIZE;
wc=0;
while (1) {
pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
if (pb) {
Log("%03d recv %d bytes\n",cn,pb);
HexDump(cn,recv_buf,pb);
Sleep(1);
} else {
Sleep(1000);
}
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;

Lock(cs);
lent=len;
if (fbuf->size+lent>BSIZE) {
lent=BSIZE-fbuf->size;
}
if (fbuf->tail+lent>BSIZE) {
len1=BSIZE-fbuf->tail;
memcpy(fbuf->data+fbuf->tail,buf ,len1);
len2=lent-len1;
memcpy(fbuf->data ,buf+len1,len2);
fbuf->tail=len2;
} else {
memcpy(fbuf->data+fbuf->tail,buf ,lent);
fbuf->tail+=lent;
}
fbuf->size+=lent;
Unlock(cs);
return lent;
}
void thdA(void *pcn) {
char *send_buf;
int send_nbytes;
int cn;
int wc;
int a;
int pa;

cn=(int)pcn;
Log("%03d thdA thread begin...\n",cn);
a=0;
while (1) {
Sleep(100);
memset(Abuf,a,ASIZE);
a=(a+1)%256;
if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
send_buf=(char *)Abuf;
send_nbytes=ASIZE;
Log("%03d sending %d bytes\n",cn,send_nbytes);
HexDump(cn,send_buf,send_nbytes);
wc=0;
while (1) {
pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
Log("%03d sent %d bytes\n",cn,pa);
HexDump(cn,send_buf,pa);
send_buf+=pa;
send_nbytes-=pa;
if (send_nbytes<=0) break;//
Sleep(1000);
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
}
int main() {
InitializeCriticalSection(&cs_log );
Log("Start===========================================================\n");
InitializeCriticalSection(&cs_HEX );
InitializeCriticalSection(&cs_BBB );

BBB.head=0;
BBB.tail=0;
BBB.size=0;

_beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
_beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);

if (!access("No_Loop",0)) {
remove("No_Loop");
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
while (1) {
Sleep(1000);
if (No_Loop) break;//
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
Sleep(3000);
DeleteCriticalSection(&cs_BBB );
DeleteCriticalSection(&cs_HEX );
Log("End=============================================================\n");
DeleteCriticalSection(&cs_log );
return 0;
}
qnetg123 2012-03-06
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 kevin_perkins 的回复:]

我觉得很有可能与CriticalSection有关系。你给的代码不全,不知道你的那个循环是怎么写的。线程之间互斥了。
[/Quote]
线程互斥是怎么一回事呢,我不懂
qnetg123 2012-03-06
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 hnwyllmm 的回复:]

楼主的循环在哪呢?
还是不太明白楼主的意思
按我自己猜测的,在这个函数里面如果有循环,肯定只能在循环退出后才能退出这个函数

如果这个循环没有退出,这个OnReceive如果有内容也不会发出,一定要等到循环退出后,
上面这句,是不是楼主写错了,“接收”写成发出了
我感觉不会,如果有数据达到就可以接收数据
[/Quote]

并不是的,我的循环在另一个函数A里边,
当我调用A,这时候A里边循环,这时候如果有东西过来,receive 不会触发
羽飞 2012-03-05
  • 打赏
  • 举报
回复
楼主的循环在哪呢?
还是不太明白楼主的意思
按我自己猜测的,在这个函数里面如果有循环,肯定只能在循环退出后才能退出这个函数

如果这个循环没有退出,这个OnReceive如果有内容也不会发出,一定要等到循环退出后,
上面这句,是不是楼主写错了,“接收”写成发出了
我感觉不会,如果有数据达到就可以接收数据
qnetg123 2012-03-05
  • 打赏
  • 举报
回复
是讲述不够清楚么,
void CClientSocket::OnReceive(int nErrorCode)
{
CSocket::OnReceive(nErrorCode);
char buffer[BUFFSIZE];
int Num = 0;
Num = this->Receive(buffer,BUFFSIZE,0);
//writeintoLog(Num);
if(Num == 0)
{
//f("socketState:{state 0}{log 与服务端连接断开!}\r\n",sock); //向客户端发送断开信息
A_event_Evalevent("socketState","{state 0}{log 与服务端连接断开!}",this->m_hSocket,RecOther);
A_Socket_Delete_LinkList(this->m_hSocket); //从Socket链表中删除该Socket
}
else if(Num < 0)
{
int i = GetLastError();
char _mess1[255];
sprintf(_mess1,"socketState:{state 0}{log 接收错误,错误ID为:%d}\r\n",i);
A_event_Evalevent("socketState",_mess1,this->m_hSocket,RecOther);
//向客户端发送断开信息
A_Socket_Delete_LinkList(this->m_hSocket); //从Socket链表中删除该Socket
}
buffer[Num] = 0;

if(Num == 9 || strcmp(buffer,"abcdefg\r\n") == 0 ) //如果是心跳节点
{
SetAliveToZero(this->m_hSocket);
goto END;
}

A_EnterCriticalSection();

Net_ThreadProc(buffer,this->m_hSocket);
A_LeaveCriticalSection();

}
然后在程序的其它地方
有个循环读取一个参数值的地方,
如果这个循环没有退出,这个OnReceive如果有内容也不会发出,一定要等到循环退出后,
本程序,实现一个简单的语音聊天功能,将麦克风采集到的音频数据经G711压缩后,通过UDP协议传输。在本文中 不讨论如何通过麦克风采集音频数据,也不讨论G711压缩的细节,相关内容可以查看文章后参考文献的内容。 系统架构如下所示: | Invite | | --------------------------------> | | OK | | <-------------------------------- | | | | --------------------------------> | | Audio flow | | <-------------------------------- | | Bye | | --------------------------------> | A B 系统所用到的命令如:Invite、OK、Bye等设计为一个枚举类型变量, enum Command { Invite, //Make a call. Bye, //End a call. Busy, //User busy. OK, //Response to an invite message. OK is sent to //indicate that call is accepted. Null, //No command. } 当用户想要语音聊天时,发送Invite消息,等待对方的反馈OK应答。当收到OK应答后,开始发送/接受 语音信息。如果对方拒绝聊天,则发送Busy信息作为应答。要终止聊天时,发送Bye消息即可。 程序在端口1450同步实现连接建立消息的收发,在端口1550异步收发聊天信息。也就是说,本程序监听 两个端口,一个负责呼叫消息,另一个负责音频数据。 监听1450端口的代码: //使用UDP clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450); //Listen asynchronously on port 1450 for //coming messages (Invite, Bye, etc). clientSocket.Bind(ourEP); //Receive data from any IP. EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0)); byteData = new byte[1024]; //Receive data asynchornously. clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref remoteEP, new AsyncCallback(OnReceive), null); 当收到发送来的消息后,根据消息类型来进行对应的处理。 private void OnReceive(IAsyncResult ar) { try { EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0); //Get the IP from where we got a message. clientSocket.EndReceiveFrom(ar, ref receivedFromEP); //Convert the bytes received into an object of type Data. Data msgReceived = new Data(byteData); //Act according to the received message. switch (msgReceived.cmdCommand) { //We have an incoming call. case Command.Invite: { if (bIsCallActive == false) { //We have no active call. //Ask the user to accept the call or not. if (MessageBox.Show("Call coming from " + msgReceived.strName + ".\r\n\r\nAccept it?", "VoiceChat", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { SendMessage(Command.OK, receivedFromEP); vocoder = msgReceived.vocoder; otherPartyEP = receivedFromEP; otherPartyIP = (IPEndPoint)receivedFromEP; InitializeCall(); } else { //The call is declined. Send a busy response. SendMessage(Command.Busy, receivedFromEP); } } else { //We already have an existing call. Send a busy response. SendMessage(Command.Busy, receivedFromEP); } break; } //OK is received in response to an Invite. case Command.OK: { //Start a call. InitializeCall(); break; } //Remote party is busy. case Command.Busy: { MessageBox.Show("User busy.", "VoiceChat", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; } case Command.Bye: { //Check if the Bye command has indeed come from the user/IP with which we have //a call established. This is used to prevent other users from sending a Bye, which //would otherwise end the call. if (receivedFromEP.Equals (otherPartyEP) == true) { //End the call. UninitializeCall(); } break; } } byteData = new byte[1024]; //Get ready to receive more commands. clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref receivedFromEP, new AsyncCallback (OnReceive), null); } catch (Exception ex) { MessageBox.Show(ex.Message, "VoiceChat-OnReceive ()", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 为了保证在收发音频数据时,不产生UI阻塞,采用多线程来异步收发数据。 private void InitializeCall() { try { //Start listening on port 1500. udpClient = new UdpClient(1550); Thread senderThread = new Thread(new ThreadStart(Send)); Thread receiverThread = new Thread(new ThreadStart(Receive)); bIsCallActive = true; //Start the receiver and sender thread. receiverThread.Start(); senderThread.Start(); btnCall.Enabled = false; btnEndCall.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "VoiceChat-InitializeCall ()", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 异步发送从麦克风采集到的音频数据 * Send synchronously sends data captured from microphone across the network on port 1550. */ private void Send() { try { //The following lines get audio from microphone and then send them //across network. captureBuffer = new CaptureBuffer(captureBufferDescription, capture); CreateNotifyPositions(); int halfBuffer = bufferSize / 2; captureBuffer.Start(true); bool readFirstBufferPart = true; int offset = 0; MemoryStream memStream = new MemoryStream(halfBuffer); bStop = false; while (!bStop) { autoResetEvent.WaitOne(); memStream.Seek(0, SeekOrigin.Begin); captureBuffer.Read(offset, memStream, halfBuffer, LockFlag.None); readFirstBufferPart = !readFirstBufferPart; offset = readFirstBufferPart ? 0 : halfBuffer; //TODO: Fix this ugly way of initializing differently. //Choose the vocoder. And then send the data to other party at port 1550. if (vocoder == Vocoder.ALaw) { byte[] dataToWrite = ALawEncoder.ALawEncode(memStream.GetBuffer()); udpClient.Send(dataToWrite, dataToWrite.Length, otherPartyIP.Address.ToString (), 1550); } else if (vocoder == Vocoder.uLaw) { byte[] dataToWrite = MuLawEncoder.MuLawEncode(memStream.GetBuffer()); udpClient.Send(dataToWrite, dataToWrite.Length, otherPartyIP.Address.ToString(), 1550); } else { byte[] dataToWrite = memStream.GetBuffer(); udpClient.Send(dataToWrite, dataToWrite.Length, otherPartyIP.Address.ToString(), 1550); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "VoiceChat-Send ()", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { captureBuffer.Stop(); //Increment flag by one. nUdpClientFlag += 1; //When flag is two then it means we have got out of loops in Send and Receive. while (nUdpClientFlag != 2) { } //Clear the flag. nUdpClientFlag = 0; //Close the socket. udpClient.Close(); } } 从端口1550处接受收到的音频数据 private void Receive() { try { bStop = false; IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); while (!bStop) { //Receive data. byte[] byteData = udpClient.Receive(ref remoteEP); //G711 compresses the data by 50%, so we allocate a buffer of double //the size to store the decompressed data. byte[] byteDecodedData = new byte[byteData.Length * 2]; //Decompress data using the proper vocoder. if (vocoder == Vocoder.ALaw) { ALawDecoder.ALawDecode(byteData, out byteDecodedData); } else if (vocoder == Vocoder.uLaw) { MuLawDecoder.MuLawDecode(byteData, out byteDecodedData); } else { byteDecodedData = new byte[byteData.Length]; byteDecodedData = byteData; } //Play the data received to the user. playbackBuffer = new SecondaryBuffer(playbackBufferDescription, devi

64,641

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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