client.c

来自「實現一套網路TCP/IP的嵌入式系統測試程式...希望可以在多平台下運行」· C语言 代码 · 共 79 行

C
79
字号
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
 
int main() { 
struct sockaddr_in addr_svr; 
  
int sockfd; 
  

char ibuf[150];
char obuf[150];
char ans[2];

// Set Server Address 
memset(&addr_svr, 0, sizeof(addr_svr)); 
addr_svr.sin_family= AF_INET; 
addr_svr.sin_port= htons(80); 
addr_svr.sin_addr.s_addr = inet_addr("192.168.0.204"); 
 
// Create Client Socket 
sockfd = socket(AF_INET, SOCK_STREAM, 0); 
  
if(sockfd == -1) { 
  printf("Error: socket()\n"); 
  exit(1); 
} 
 
// Connect to Server 
if(connect(sockfd,(struct sockaddr *)&addr_svr, sizeof(addr_svr)) == -1){ 
  printf("Error: connect()\n"); 
  exit(1); 
}

printf("Want to play?\n");
scanf("%s", ans);
while (!strcmp(ans,"y"))
{
  write(sockfd, ans, 2);
  
  read(sockfd, ibuf, sizeof(ibuf));
  printf("%s\n", ibuf);
  scanf("%s", obuf);
  write(sockfd, obuf, strlen(obuf)+1);

  read(sockfd, ibuf, sizeof(ibuf));
  printf("%s\n", ibuf);
  scanf("%s", obuf);
  write(sockfd, obuf, strlen(obuf)+1);  

  read(sockfd, ibuf, sizeof(ibuf));
  printf("%s\n", ibuf);
  
  printf("Want to play?\n");
  scanf("%s", ans);
}
// Write String to Server 

//write(sockfd, buf_money, strlen(buf_money)+1);

//printf("Which one would you choose?\n "); 
//scanf("%s", buf_money); 
//write(sockfd, buf_money, strlen(buf_money)+1);  
 
// Read String from Server 
  //read(sockfd, obuf, sizeof(obuf)); 
  
// Output result 
//printf("[Echo From Server] %s\n", obuf); 
  
// Close socket 
close(sockfd); 
 
return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?