Linux网络编程系列-TCP编程实例

实例:

client

 

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
const int MAXLINE = 100;
void str_cli(int sockfd) {
  char recvline[MAXLINE];
  string str;
  getline(cin, str);
  while (!str.empty()) {
    send(sockfd, str.c_str(), str.size(), 0);
    if (recv(sockfd, recvline, MAXLINE, 0) != -1) {
      cout << "receive from server:" << recvline << endl;
    }
    getline(cin, str);
  }
}

int main() {
  int sockfd;
  struct sockaddr_in servaddr;
  
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(8000);
  inet_pton(AF_INET, "10.3.17.75", &servaddr.sin_addr);

  connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
  str_cli(sockfd);
  exit(0);
}


server

 

 

#include <sys/socket.h>
#include <netinet/in.h>
void str_echo(int sockfd) {
  size_t n;
  char line[MAXLINE];
  while(true) {
    if ((n = recv(sockfd, line, MAXLINE, 0)) == 0)
      return;
    cout << "from client:" << line << endl;
    send(sockfd, line, n, 0);
  }
}

int main(int argc, char** argv) {
  int listenfd, connfd;
  socklen_t clilen;
  struct sockaddr_in cliaddr, servaddr;

  listenfd = socket(AF_INET, SOCK_STREAM, 0);

  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(8000);
  bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
  
  listen(listenfd, 0);
  while (true) {
    clilen = sizeof(cliaddr);
    connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &clilen);
    if ( 0 == fork() ) {
      close(listenfd);
      str_echo(connfd);
      exit(0);
    }
    close(connfd);
  }
}

 

转载于:https://www.cnblogs.com/whuqin/p/4982001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值