📄 socketclient.c
字号:
// SOCKET通讯#include <stdio.h> /* Standard input/output definitions */#include <string.h> /* String function definitions */#include <unistd.h> /* UNIX standard function definitions */#include <fcntl.h> /* File control definitions */#include <errno.h> /* Error number definitions */#include <termio.h> /* POSIX terminal control definitions */#include <sys/time.h>#include <sys/select.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#include <time.h>#include <math.h>#include <stdlib.h>#include <sys/signal.h>#include "posmsg.c"
#define PROMPT "你想终止程序吗?\n"
char *prompt = PROMPT;
int msqid;
int debug; //1-log,0-no logint iPortDevice;char * chrHostName = "localhost"; // bad functionint iPort; // = 11001;/**************************** start of tools ****************************/// 获得当前时间long getCurrTime(){ long currTime; time( &currTime ); //printf( "Time in seconds since UTC 1/1/70:\t%ld\n", currTime ); return currTime;}void mylog(char *filename,char *log,int len){ FILE *fd; int k; if( (fd = fopen( filename, "a+" )) == NULL ){ if(debug) printf("\n\r[ERROR]: Open log file failure\n" ); exit(0); } if(debug) printf("\n\r写日志\n" ); fwrite(log,sizeof(char),len,fd); fflush(fd); fclose(fd);}void int2chr(char *chrOut, int iIn){ int iTmp = 0; iTmp = iIn; iTmp = iTmp/1000; chrOut[0] = (char)(iTmp + 48); iIn = iIn - iTmp*1000; iTmp = iIn; iTmp = iTmp/100; chrOut[1] = (char)(iTmp + 48); iIn = iIn - iTmp*100; iTmp = iIn; iTmp = iTmp/10; chrOut[2] = (char)(iTmp + 48); iIn = iIn - iTmp*10; iTmp = iIn; chrOut[3] = (char)(iTmp + 48); if(debug) printf("\nint2chr is %c%c%c%c\n",chrOut[0],chrOut[1],chrOut[2],chrOut[3]); return;}int chr2int(char *chrIn){ int iOut = atoi(chrIn); if (iOut<1) iOut = 0; if(debug) printf("\nchr2int is %d\n",iOut); return iOut;}int sendLength(int iLength){ char chrSend[4]; int2chr(chrSend, iLength); return(sendPkgByLen(chrSend,4)); }void sendPackage(unsigned char *pack,int len){ sendLength(len); sendPkgByLen((char *)pack,len);}//读二进制文件
int readfile(char *filename,unsigned char *buf){
FILE *stream;
int ch ,len = 0;
if( (stream = fopen( filename,"rb")) == NULL ){
printf( "文件打开失败!\n" );
return -1;
}
while ((ch = fgetc(stream)) != EOF){
buf[len++] = (unsigned char)ch;
// printf( "[%02x]",ch );
}
fclose( stream );
return len;
}
/**************************** end of tools ****************************//**************************** start of socket ****************************/void init_Socket(){ struct sockaddr_in saServer; struct hostent *heHost, *gethostbyname(); struct timeval tv; fd_set readfds; int dot_i = 0; tv.tv_sec = 0; tv.tv_usec = 50000; iPortDevice = socket(AF_INET, SOCK_STREAM, 0); if (iPortDevice < 0) { if(debug) printf("Can't create a socket!!!\n"); exit(1); } heHost = gethostbyname(chrHostName); if (heHost == NULL){ if(debug) printf("%s is a unknown host\n", chrHostName); exit(2); } iPortDevice = socket(AF_INET, SOCK_STREAM, 0); saServer.sin_family = AF_INET; memcpy(&saServer.sin_addr, heHost->h_addr, heHost->h_length); saServer.sin_port = htons(iPort); if(debug){ printf("Try to connect to Server...\n"); printf("waiting a few minutes."); } while (1) { if (connect(iPortDevice, (struct sockaddr *) &saServer, sizeof(saServer)) >= 0) break; if (errno == ECONNREFUSED) { dot_i++; if (dot_i % 60 == 0){ if(debug) printf("."); fflush(stdout); //if (dot_i % (60*80) == 0) // printf("\n"); } close(iPortDevice); iPortDevice = socket(AF_INET, SOCK_STREAM, 0); if (iPortDevice < 0) { if(debug) printf("Create stream socket error!!!"); exit(1); } }else { if(debug) printf("Connect Failed!!!"); exit(1); } } if(debug) printf("iPortDevice success!");}void receivePkg(int iLen,unsigned char *chrReceive){ int iReceive = 0; int iCount = 0; while (iCount < iLen){ iReceive = read(iPortDevice, chrReceive + iCount, iLen - iCount); if (iReceive == 0) break; if (iReceive == -1) { printf("receive pkg error!!!\n"); }else if (iReceive > 0){ //printf("receive pkg success!!!\n %s\n", chrReceive); iCount += iReceive; } }}int sendPkgByLen(char *chrSend, int iLen){ int iSend = 0; int iCount = 0; while (iCount < iLen) { iSend = write(iPortDevice, chrSend + iCount, iLen - iCount); if (iSend == -1) { if(debug) printf("Send failed !!!\n"); return -1; } if(debug) printf("already send %d\n",iSend); iCount += iSend; } return 0;}int sendPkg(char *chrSend){ int iSend = 0; int iCount = 0; int iLen = strlen(chrSend); while (iCount < iLen) { iSend = write(iPortDevice, chrSend + iCount, iLen - iCount); if (iSend == -1) { if(debug) printf("Send failed !!!\n"); return -1; } if(debug) printf("already send %d\n",iSend); iCount += iSend; } return 0;}int receiveLength(){ char *chrInt; int iReceive = 0; int iCount = 0; int ret; chrInt = (char *)malloc(4); while (iCount < 4){ iReceive = read(iPortDevice,chrInt + iCount,4 - iCount); if (iReceive == 0){ ret = 0; break; } if (iReceive < 0) { printf("receive pkg error!!!"); ret = -1; break; }else{// printf("\nreceive len success!!!\n %s\n", chrInt); iCount += iReceive; ret=chr2int(chrInt); free(chrInt); } } return ret;}/**************************** end of socket ****************************/// 处理信号void ctrl_c_op(int signo){
char c;
write(STDERR_FILENO,prompt,strlen(prompt));
fflush(stdin);
c = getchar();
if (c == 'y'|| c == 'Y'){
delmsg(msqid);// 删除消息队列
exit(0);
}
}
//主程序int main(int argc,char *argv[]){ unsigned char buffer[1024],rcvBuf[1024],rcvPack[1024]; int Len = 0,rcvLen = 0,packlen,i,timeout; long currTime1,currTime2; char logfile[10]="jznx.log",logmsg[1024]; int loglen; struct sigaction act; // 设置退出信号
int msgqtype; // 1 为从 com 到 mon ,2 为从 mon 到 socketc ,3 为从 socketc 到 mon // act.sa_handler = ctrl_c_op;
sigemptyset(&act.sa_mask); // 将信号集合设置为空
act.sa_flags = 0;
if(sigaction(SIGQUIT,&act,NULL) < 0){ // CTRL-\ 退出当前进程,并生成主存储文件
fprintf(stderr,"Install Signal Action Error:%s\n\a",strerror(errno));
exit(1);
}
if(argc>3){ // 得到输入参数(Socket端口,调试输出标致) iPort=atoi(argv[1]); timeout=atoi(argv[2]); debug=atoi(argv[3]); }else{ strcpy(logmsg,"\nPlease input Serial port Socket port debug, eg:\nsocketc 11001 30 0\n"); loglen=strlen(logmsg); logmsg[loglen]='\0'; mylog(logfile,logmsg,loglen); //写日志 printf("%s",logmsg); exit(0); } msqid = createmsg(0777); // 创建需处理消息队列的 client 端
// printf("\n从 mon 接收待处理的数据\n"); msgqtype = 2; Len = receivemsg(buffer,msqid,msgqtype); // 接收需处理的数据// printf("\n[%02x]\n",buffer[0]); if( buffer[0] == '\0'){ // 没有需处理的数据 msgqtype = 3; sendmsgs(buffer,Len,msqid,msgqtype); // 发送空数据
exit(0);
}// printf("打开文件读已处理数据...\n");// rcvLen = readfile("OUT97SEN",rcvBuf);// printf("\nlenth:%i\n",rcvLen);// printf("\n创建 Socket 连接并打开!\n"); init_Socket(); sendPackage(buffer,Len); // 向 Java Socket 发送数据// printf("\n送完!\n"); currTime1=getCurrTime();// while(1){ rcvLen = receiveLength(); // 接收数据 from Java Socket// printf("rcvLen=%d\n",rcvLen); if (rcvLen > 0){ memset(rcvBuf,0,rcvLen+1); receivePkg(rcvLen,rcvBuf);// printf("向 mon 送已处理数据...\n"); msgqtype = 3; sendmsgs(rcvBuf,rcvLen,msqid,msgqtype); // 发送已处理的数据
break;
}
currTime2 = getCurrTime();// printf("\ntime=%d\n",timeout); if( (currTime2-currTime1) < timeout){ rcvBuf[0] = '\0'; rcvLen = 1; msgqtype = 3; sendmsgs(rcvBuf,rcvLen,msqid,msgqtype); // 发送空数据
// printf("正在处理数据!\n"); }else{ // 超时结束// printf("处理超时!\n"); rcvBuf[0] = '\0\0'; rcvLen = 2; msgqtype = 3; sendmsgs(rcvBuf,rcvLen,msqid,msgqtype); // 发送空数据
break; } } if (iPortDevice <> -1) { close(iPortDevice); // 关闭Socket// printf("\n关闭Socket!\n"); } exit(0);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -