server 端: void *recvData(void *arg) { char recvbuf[1024]; int conn = *(int *)arg; while(1) { memset(recvbuf,0,1024); recv(conn, recvbuf, sizeof(recvbuf),0); } } main 函數: int listenfd; int conn; char sendbuf[1024]; char recvbuf[1024]; char sig_strength[16]; char radio_if[16]; if ((listenfd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) LOGE("socket error"); unlink("/tmp/test_socket"); //地址複用 struct sockaddr_un servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; strcpy(servaddr.sun_path, "/tmp/test_socket"); if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) LOGE("bind error"); if (listen(listenfd, SOMAXCONN) < 0) LOGE("listen error"); while(1) { conn = accept(listenfd, NULL, NULL); if (conn == -1) { if (conn == EINTR) continue; } pthread_create(&thread_socket_recv, NULL, recvData, &conn); while(1) { memset(sendbuf,0,1024); strncpy(sendbuf,"xxxx, strlen("xxx")); send(conn, sendbuf, strlen(sendbuf),0); } close(conn); close(listenfd); } client端(非阻塞socket) typedef struct QMISocket{ int socketfd; struct timeval timeout; pthread_mutex_t mMutex; }QMISocket; extern QMISocket mSocket; static int sockConnect() { struct sockaddr_un servaddr; int retval ; fd_set set; int flags; int ret=-1; if ((mSocket.socketfd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) printf("socket error"); mSocket.timeout.tv_sec = 3; mSocket.timeout.tv_usec = 0; setsockopt(mSocket.socketfd,SOL_SOCKET,SO_SNDTIMEO,(char *)&(mSocket.timeout),sizeof(struct timeval)); setsockopt(mSocket.socketfd,SOL_SOCKET,SO_RCVTIMEO,(char *)&(mSocket.timeout),sizeof(struct timeval)); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; strcpy(servaddr.sun_path, "/tmp/test_socket"); flags = fcntl(mSocket.socketfd, F_GETFL, 0); fcntl(mSocket.socketfd, F_SETFL, flags | O_NONBLOCK); ret = connect(mSocket.socketfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); if (0 == ret) { printf("connected\n"); } else{ if (errno != EINPROGRESS) { perror("connect"); return-1; } FD_ZERO(&set); FD_SET(mSocket.socketfd,&set); retval = select(mSocket.socketfd+ 1,NULL, &set,NULL,&mSocket.timeout); if(retval==-1) { perror("select"); return -1; } else if(retval== 0) { fprintf(stderr,"timeout\nn"); printf("%d\n",time(NULL)); return 0; } printf("connected\n"); } } flags = fcntl(mSocket.socketfd, F_GETFL, 0); fcntl(mSocket.socketfd, F_SETFL, flags & ~O_NONBLOCK); return mSocket.socketfd; } int main() { while(1)//wait the reboot-daemon { if (sockConnect() > 0) break; sleep(1); } while(1) { char recvbuf[1024]={0}; ret = recv(mSocket.socketfd, recvbuf, sizeof(recvbuf),0); } }
這裏在recv的時候,若是send端發送很是快,那麼可能會致使一次recv到多個數據包的狀況,那可須要在每一個數據包結尾打上標記,表示一個個數據包。recv根據這些flags去截取每個數據包socket
char *remainBuf = NULL; remainBuf = recvbuf; char *tmp = strstr(remainBuf, "@"); memset(key,0,1024); if (tmp != NULL) { strncpy(key, remainBuf, tmp - remainBuf); remainBuf = remainBuf+(tmp - remainBuf)+1; }