search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[C語言] 一組socket server client send string的程式範例

先收下改天必有用處

Server Code
/******************* SERVER CODE *****************/

#include
#include
#include
#include
#include

int main(){
  int welcomeSocket, newSocket, portNum, clientLen, nBytes;
  char buffer[1024];
  struct sockaddr_in serverAddr;
  struct sockaddr_storage serverStorage;
  socklen_t addr_size;
  int i;

  welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);

  portNum = 7891;
  
  serverAddr.sin_family = AF_INET;
  serverAddr.sin_port = htons(portNum);
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));

  if(listen(welcomeSocket,5)==0)
    printf("Listening\n");
  else
    printf("Error\n");

  addr_size = sizeof serverStorage;

  /*loop to keep accepting new connections*/
  while(1){
    newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);
    /*fork a child process to handle the new connection*/
    if(!fork()){
      nBytes = 1;
      /*loop while connection is live*/
      while(nBytes!=0){
        nBytes = recv(newSocket,buffer,1024,0);
  
        for (i=0;i
          buffer[i] = toupper(buffer[i]);
        }

        send(newSocket,buffer,nBytes,0);
      }
      close(newSocket);
      exit(0);
    }
    /*if parent, close the socket and go back to listening new requests*/
    else{
      close(newSocket);
    }
  }

  return 0;
}


Client Code


/******************* CLIENT CODE *****************/

#include
#include
#include
#include

int main(){
  int clientSocket, portNum, nBytes;
  char buffer[1024];
  struct sockaddr_in serverAddr;
  socklen_t addr_size;

  clientSocket = socket(PF_INET, SOCK_STREAM, 0);

  portNum = 7891;

  serverAddr.sin_family = AF_INET;
  serverAddr.sin_port = htons(portNum);
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  addr_size = sizeof serverAddr;
  connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);

  while(1){
    printf("Type a sentence to send to server:\n");
    fgets(buffer,1024,stdin);
    printf("You typed: %s",buffer);

    nBytes = strlen(buffer) + 1;

    send(clientSocket,buffer,nBytes,0);

    recv(clientSocket, buffer, 1024, 0);

    printf("Received from server: %s\n\n",buffer);   
  }

  return 0;
}


熱門推薦

本文由 charleslin74pixnetnetblog 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦