Linux socket测试程序

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);
   //pthread_join(recvThreadID,)
   exit(0);
}

操作

mkdir build
cd build
cmake ..
make VERBOSE=1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值