socket简单应用客户端代码

client.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <sys/unistd.h>
#define PORT        8999
#define DESIP  "127.0.0.1"
#define MAXSIZE     (8 * 4096)
int main(int argc, char *argv[])
{
    int sockfd;
    struct sockaddr_in des_addr;
    char sendmsg[MAXSIZE], recvmsg[MAXSIZE]; 
        
    sockfd = socket(AF_INET, SOCK_STREAM, 0);//创建socket
    if (sockfd < 0) {
        perror("socket error");
        return -1;
    }
    
 /* 设置连接目的地址 */
    des_addr.sin_family = AF_INET;
    des_addr.sin_port = htons(PORT);
    des_addr.sin_addr.s_addr = inet_addr(DESIP);
    bzero(&(des_addr.sin_zero), 8);
 
 /* 发送连接请求 */
    if (connect(sockfd, (struct sockaddr *)&des_addr, sizeof(struct sockaddr)) < 0) {
  perror("connect failed");
        return -1;
    }
 printf("enter the msg you want to send, enter \"quit\" to quit!\n");
    while (1) {
        memset(sendmsg, 0, MAXSIZE);
        memset(recvmsg, 0, MAXSIZE);
        printf("client:\n");
     gets(sendmsg);
            
     if (send(sockfd, sendmsg, strlen(sendmsg) + 1, 0) < 0) {//发送信息
   printf("send msg failed!");
            close(sockfd);
         return -1;
     }
        
  if (!strcmp(sendmsg, "quit")) {
   printf("quit success!\n");
            break;
        }
        memset(recvmsg, 0, MAXSIZE);
        if (recv(sockfd, recvmsg, MAXSIZE, 0) < 0) {//接收信息
   printf("\nserver has no reply!\n");
            close(sockfd);
        }
        printf("server:\n%s\n", recvmsg);
    }
    close(sockfd); //关闭套接字          return 0;     }
相关文章
相关标签/搜索