CMakeFilelists
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
SET(CMAKE_VERBOSE_MAKEFILE ON)
SET(CMAKE_C_COMPILER "gcc")
PROJECT(HELLO)
SET(CLIENT_FILE "./client.c" )
LINK_LIBRARIES(pthread)
ADD_EXECUTABLE(client ${CLIENT_FILE})
client.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pthread.h>
const char *serverIP = "192.168.3.9";
int serverPort = 7888;
int threadRun = 0;
int sockfd;
int retval = -1;
char recvbuf[1024];
void *startRecvThread(void *args){
while(threadRun == 0){
sleep(1);
}
for(;;){
if(threadRun == 0)
pthread_exit(&retval);
int len = recv(sockfd,recvbuf,1024,0);
if(len<0){
fprintf(stderr, "recv Error:%s\a\n", strerror(errno));
pthread_exit(&retval);
}else if(len>0){
recvbuf[len] = 0;
printf("recv:%s\n",recvbuf);
}
}
}
int main(int argc, char *argv[])
{
char sendbuffer[200];
char recvbuffer[200];
struct sockaddr_in server_addr;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "Socket Error:%s\a\n", strerror(errno));
exit(1);
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(serverPort);
server_addr.sin_addr.s_addr = inet_addr(serverIP); ;
if (connect(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "Connect error:%s\n", strerror(errno));
exit(1);
}
pthread_t recvThreadID ;
threadRun = 1;
int ret = pthread_create(&recvThreadID,NULL,startRecvThread,NULL);
for(int i=0;i<10;i++)
{
sprintf(sendbuffer,"hello %d\n",i);
int len = strlen(sendbuffer);
send(sockfd, sendbuffer,len, 0);
printf("send %s",sendbuffer);
sleep(1);
}
close(sockfd);
exit(0);
}
操作
mkdir build
cd build
cmake ..
make VERBOSE=1