簡易的C/S系統(實現兩個數的和)

來源:互聯網
上載者:User

標籤:

//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\n", 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("伺服器等待訊息\n"); 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, 連接埠號碼是:\n", inet_ntoa(client_address2->sin_addr)); read(client_sockfd, &num1, sizeof(num1)); printf("第一個數是: %d\n", num1); read(client_sockfd, &num2, sizeof(num2)); printf("第二個數是: %d\n", num2); num3 = num1 + num2; write(client_sockfd, &num3, sizeof(num3)); close(client_sockfd); } return 0;}

 

簡易的C/S系統(實現兩個數的和)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.