c socket

server.c
服務端創建邏輯:

  1. 建立socket(socket())
  2. 綁定ip 與端口(bind())
  3. 監聽客戶端請求(accept())(阻塞)
  4. 給客戶端返回數據(send())
    注意:通信是根據connectfd (int),可以當做是連接id,通過此id 可以找到客戶端
    fd=file description 文件描述符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<errno.h>
#include <sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>



#define LISTEN_PORT 8000
#define MAX_BYTES_LINE 4096


int main(int argc,char **argv){

int sockfd,connectfd;
int dataLen=0;
int i_listenPort=8000;

char buffer[MAX_BYTES_LINE];
char * c_ipAddr="127.0.0.1";
char * c_responseInfo="Hello,you are connected!\n";
struct sockaddr_in serverAddr;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){

printf("create server socket error:%s(errno:%d)\n",strerror(errno),errno);
    exit(0);
}
memset(&serverAddr,0,sizeof(serverAddr));
serverAddr.sin_family=AF_INET;
serverAddr.sin_addr.s_addr=htonl(INADDR_ANY);//auto get local server ip addr
serverAddr.sin_port=htons(LISTEN_PORT);

if(bind(sockfd,(struct sockaddr*) & serverAddr,sizeof(serverAddr))==-1){
printf("bind socket error:%s(errno:%d)\n",strerror(errno),errno);
exit(0);
}
if(listen(sockfd,10)==-1){
    printf("listen socket error :%s(errno:%d)\n",strerror(errno),errno);
exit(0);
}
printf("waiting for client to connect\n");
while(1){
    if((connectfd=accept(sockfd,(struct sockaddr *)NULL,NULL))==-1){
       printf("accept socket error:%s(errorno:%d)",strerror(errno),errno);
     continue;
    }
    dataLen=recv(connectfd,buffer,MAX_BYTES_LINE,0);
    if(!fork()){ //in sub process ,fork() will return 0
        if(send(connectfd,c_responseInfo,strlen(c_responseInfo),0)==-1){
            perror("send response error");
            close(connectfd);
            exit(0);
        }
         buffer[dataLen]='\0';
         printf(" recv msg from client connectfd: %d,\ncontent:%s\n",connectfd,buffer);
        close(connectfd);// close connection
    }
   
}

close(sockfd);


}

client.c

客戶端邏輯:

  1. 建立socket
  2. 連接server(connect())\
  3. 發送數據(send())
  4. 讀取返回數據(recv())
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MAX_BYTES_LINE 4096

int main(int argc, char **argv)
{

    int sockfd, n, recv_len;
    char recvLine[MAX_BYTES_LINE], 
         sendLine[MAX_BYTES_LINE];
    char buffer[MAX_BYTES_LINE];
    char *c_ipAddr = "127.0.0.1";
    int i_port = 8000;
    struct sockaddr_in serverAddr;
    if (argc == 1)
    {

        printf("this client will connect server message:ip=127.0.0.1,Prot=8000\n");
    }

    else if (argc == 2)
    {

        c_ipAddr = argv[1];
        printf("this client will connect server message:ip=%s,port=8000\n", c_ipAddr);
    }
    else if (argc == 3)
    {

        c_ipAddr = argv[1];
        i_port = atoi(argv[2]);
        printf("this client will connect server message:IP=%s,port=%d\n", c_ipAddr, i_port);
    }
    else
    {

        printf(" usage:./client <ipaddress> and port\n");
        exit(0);
    }

// 1. create client socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("create socket error:%s(errno:%d)\n", strerror(errno), errno);
        exit(0);
    }

    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(i_port);
    if (inet_pton(AF_INET, c_ipAddr, &serverAddr.sin_addr) <= 0)// 地址轉換,10進制數轉二進制
    {
        printf("inet_pton error for %s\n", argv[1]);
        exit(0);
    }
    // 2. connect to server 
    if(connect(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr))<0){
        printf("connect error :%s)errno:%d)\n",strerror(errno),errno);
        exit(0);
    }
    //3. send data to server
    printf("send msg to Server:\n");
    fgets(sendLine,MAX_BYTES_LINE,stdin);

    if(send(sockfd,sendLine,strlen(sendLine),0)==-1){
     printf("send msg error :%s(errno:%d)",strerror(errno),errno);
     exit(0);
    }
    //4, read data from server
    if((recv_len=recv(sockfd,buffer,MAX_BYTES_LINE,0))==-1){
        perror("recv error");
        exit(1);
    }
     buffer[recv_len]='\0';
     printf("received :%s",buffer);
     close(sockfd);
     exit(0);
    

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章