Skip to content
On this page

TCP服务器客户端示例代码


标签:代码片段C/unix  

参考:TCP模型图

TcpSer.c

c
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define ERR_MSG(msg)                        \
  do {                                      \
    fprintf(stderr, "line:%d\n", __LINE__); \
    perror(msg);                            \
  } while (0)

#define IP "192.168.31.128"

int main(int argc, const char *argv[]) {
  // 创建流式套接字
  int sfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sfd < 0) {
    ERR_MSG("socket");
    return -1;
  }

  // 允许端口被快速重复使用,当检测到该端口号没有被进程正常占用时候
  // 允许端口快速被新的进程占用覆盖
  int reuse = 1;
  if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
    ERR_MSG("setsockopt");
    return -1;
  }
  printf("允许端口快速重复使用\n");

  // 填充服务器的地址信息结构体
  // 该真实结构体根据地址族制定:AF_INET:man 7 ip
  struct sockaddr_in sin;
  sin.sin_family = AF_INET;    // 必须填充 AF_INET
  sin.sin_port = htons(6666);  // 端口号的网络字节序 1024~49151
  sin.sin_addr.s_addr = inet_addr(IP);  // IP, 本机IP, ifconfig

  // 绑定 -----> 必须绑定
  // 功能:将服务器的 IP 地址和端口绑定到服务器套接字文件中
  if (bind(sfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
    ERR_MSG("bind");
    return -1;
  }
  printf("bind success __%d__\n", __LINE__);

  // 将套接字设置为被监听状态
  if (listen(sfd, 128) < 0) {
    ERR_MSG("listen");
    return -1;
  }
  printf("listen success __%d__\n", __LINE__);

  struct sockaddr_in cin;  // 存储连接成功的客户端地址信息
  socklen_t addrlen = sizeof(cin);
  // 从已完成连接的队列中获取一个客户端信息,生成一个新的文件描述符
  int newfd = accept(sfd, (struct sockaddr *)&cin, &addrlen);
  if (newfd < 0) {
    ERR_MSG("accept");
    return -1;
  }
  printf("[%s : %d] newfd = %d 连接成功 __%d__\n", inet_ntoa(cin.sin_addr),
         ntohs(cin.sin_port), newfd, __LINE__);

  char buf[128] = "";
  ssize_t res = 0;
  while (1) {
    // 对字符串的操作,操作之前或者之后要清空
    // 防止之前的数据对这次操作有干扰
    bzero(buf, sizeof(buf));
    // 接收
    res = recv(newfd, buf, sizeof(buf), 0);
    if (res < 0) {
      ERR_MSG("recv");
      return -1;
    } else if (0 == res) {
      printf("[%s : %d] newfd = %d 客户端已下线 __%d__\n",
             inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, __LINE__);
      break;
    }
    printf("[%s : %d] newfd = %d : %s __%d__\n", inet_ntoa(cin.sin_addr),
           ntohs(cin.sin_port), newfd, buf, __LINE__);
    // 发送
    strncat(buf, "*_*", 3);
    if(send(newfd, buf, sizeof(buf), 0) < 0) {
      ERR_MSG("send");
      return -1;
    }
    printf("发送成功\n");
  }

  // 关闭文件描述符
  close(sfd);
  close(newfd);

  return 0;
}

TcpCli.c

c
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define ERR_MSG(msg)                        \
  do {                                      \
    fprintf(stderr, "line:%d\n", __LINE__); \
    perror(msg);                            \
  } while (0)

#define IP "192.168.31.128"

int main(int argc, const char *argv[]) {
  // 创建流式套接字
  int cfd = socket(AF_INET, SOCK_STREAM, 0);
  if (cfd < 0) {
    ERR_MSG("socket");
    return -1;
  }

  // 绑定 -----> 必须绑定
  // 功能:将客户端的 IP 地址和端口绑定到客户端套接字文件中
  // 如果不绑定,则操作系统会自动给客户端绑定上本机 IP 和随机端口: 49152~65535

  // 填充服务器的地址信息结构体
  // 该真实结构体根据地址族制定:AF_INET:man 7 ip
  struct sockaddr_in sin;
  sin.sin_family = AF_INET;    // 必须填充 AF_INET
  sin.sin_port = htons(6666);  // 端口号的网络字节序 1024~49151
  sin.sin_addr.s_addr = inet_addr(IP);  // IP, 本机IP, ifconfig

  // 连接服务器
  if (connect(cfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
    ERR_MSG("connect");
    return -1;
  }
  printf("connect success\n");

  char buf[128] = "";
  ssize_t res = 0;
  while (1) {
    printf("请输入>>> ");
    fgets(buf, sizeof(buf), stdin);
    buf[strlen(buf) - 1] = '\0';
    // 发送
    if (send(cfd, buf, sizeof(buf), 0) < 0) {
      ERR_MSG("send");
      return -1;
    }
    printf("发送成功\n");
    // 对字符串的操作,操作之前或者之后要清空
    // 防止之前的数据对这次操作有干扰
    bzero(buf, sizeof(buf));
    // 接收
    res = recv(cfd, buf, sizeof(buf), 0);
    if (res < 0) {
      ERR_MSG("recv");
      return -1;
    } else if (0 == res) {
      printf("服务器下线\n");
      break;
    }
    printf("%s __%d__\n", buf, __LINE__);
  }

  // 关闭文件描述符
  close(cfd);

  return 0;
}

Last updated: