- 論壇徽章:
- 15
|
本帖最后由 yulihua49 于 2011-07-07 16:11 編輯
回復(fù) yulihua49
有沒(méi)有例子讓我參考參考,謝謝!
mikzh 發(fā)表于 2011-07-07 15:11 ![]()
這是我的包頭:- #define HEADPACKLENGTH 48
- #define PARANUM 9
- #define PROTO_NUM para[0] /*協(xié)議號(hào):
- 客戶(hù)呼叫服務(wù)器時(shí)是調(diào)用號(hào),
- 服務(wù)器返回時(shí)是事件號(hào),1-65535 */
- #define ERRNO1 para[1] /*主錯(cuò)誤碼 */
- #define ERRNO2 para[2] /*輔助錯(cuò)誤碼 */
- #define PKG_REC_NUM para[3] /*數(shù)據(jù)記錄數(shù) */
- #define PKG_LEN para[4] /*數(shù)據(jù)包長(zhǎng)度 */
- #define T_LEN para[5] /* 傳輸長(zhǎng)度 */
- #define O_NODE para[6] /*原結(jié)點(diǎn)地址*/
- #define D_NODE para[7] /*目的結(jié)點(diǎn)描述*/
- #define PKG_CRC para[8] /*數(shù)據(jù)包CRC */
- typedef struct { /*協(xié)議頭 */
- u_int para[PARANUM];
- char *data;
- } T_NetHead;
復(fù)制代碼 9個(gè)整數(shù)共36字節(jié)。轉(zhuǎn)化成BASE64,變成48字節(jié)。因此,我的包頭是固定長(zhǎng)度48字節(jié)。
接收端按固定長(zhǎng)度48先收包頭。
然后根據(jù)T_LEN收數(shù)據(jù)。- int RecvNet(int s,char *buf,int n,int timeout)
- {
- int bcount,br,ret,num=0;
- struct timeval tmout;
- if(!buf) return 0;
- tmout.tv_sec=timeout;
- tmout.tv_usec=0;
- ret=setsockopt(s,SOL_SOCKET,SO_RCVTIMEO,(char *)&tmout,sizeof(tmout));
- *buf=0;
- if(n<=0) return 0;
- bcount=0;
- br=0;
- num=0;
- while(bcount<n){
- if((br=read(s,buf,n-bcount))>0){
- bcount+=br;
- buf+=br;
- continue;
- }
- if(br<0){
- if(errno==11) return TIMEOUTERR;
- ShowLog(1,"%s:br=%d,err=%d,%s",__FUNCTION__,br,errno,strerror(errno));
- return -1;
- }
- if(!br ) {
- if( ++num>100) break;
- usleep(5000);
- continue;
- } else num=0;
- }
- if(bcount<=0) {
- ShowLog(1,"%s:bcount=%d,err=%d,%s",__FUNCTION__,bcount,errno,strerror(errno));
- return -1;
- }
- return bcount;
- }
復(fù)制代碼 參數(shù)n就是要收的數(shù)據(jù)。如果讀的不夠數(shù),就不斷的讀,直到夠數(shù)或超時(shí)。 |
|