zoukankan      html  css  js  c++  java
  • 简易的C/S系统(实现两个数的和)

    //Client:
    #include <string.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> int main(int argc, char **argv){ int sockfd; struct sockaddr_in address; int result; int num1 = 25, num2 = 30, num3 = 0; printf("请输入两个整数"); scanf("%d%d", &num1, &num2); sockfd = socket(AF_INET,SOCK_STREAM, 0); address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = 6666; result = connect(sockfd, (struct sockaddr *) &address, sizeof(address)); if(result == -1){ perror("连接失败了"); return 1; } write(sockfd, &num1, sizeof(num1)); write(sockfd, &num2, sizeof(num2)); read(sockfd, &num3, sizeof(num3)); printf("两个数的和是%d ", num3); close(sockfd); return 0; }
    //Server
    include<stdio.h> #include<string.h> #include<sys/socket.h> #include<netinet/in.h> int main(int argc, int **argv){ int server_sockfd, client_sockfd; struct sockaddr_in server_address; struct sockaddr_in client_address; //struct sockaddr_in *client_address2; server_sockfd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr("127.0.0.1"); server_address.sin_port = 6666; bind(server_sockfd, (struct sockaddr *) &server_address, sizeof(server_address)); listen(server_sockfd, 10); int client_len; //char client_ip[100], client_port[100]; while(1){ int num1, num2, num3; printf("服务器等待消息 "); client_len = sizeof(client_address); client_sockfd = accept(server_sockfd, (struct sockaddr *) &client_address, (socklen_t *__restrict) &client_len); //sprintf(client_ip, inet_ntoa(client_address.sin_addr)); //client_address2 = (struct sockaddr_in *)&client_address; //printf("你所连接的主机的ip地址为: %s, 端口号是: ", inet_ntoa(client_address2->sin_addr)); read(client_sockfd, &num1, sizeof(num1)); printf("第一个数是: %d ", num1); read(client_sockfd, &num2, sizeof(num2)); printf("第二个数是: %d ", num2); num3 = num1 + num2; write(client_sockfd, &num3, sizeof(num3)); close(client_sockfd); } return 0; }
  • 相关阅读:
    diy_markdown 的 html 显示
    根据 vuex 的 this.$store.dispatch() 返回值 处理逻辑
    vue 项目配置: 局域网 ip 发布
    vue-markdown 之 markdown-it, 以及 table of content 的实现:markdown-it-toc-and-anchor
    程序员面试金典-面试题 08.05. 递归乘法
    程序员面试金典-面试题 08.04. 幂集
    程序员面试金典-面试题 08.03. 魔术索引
    程序员面试金典-面试题 08.02. 迷路的机器人
    程序员面试金典-面试题 08.01. 三步问题
    程序员面试金典-面试题 05.08. 绘制直线
  • 原文地址:https://www.cnblogs.com/handsomecui/p/5674667.html
Copyright © 2011-2022 走看看