c - 如何使用套接字编程一次发送三个字符

标签 c sockets

我将以下缓冲区存储在二维字符缓冲区中:

char buff1[][3]= {{0xff , 0xfd, 0x18},{0xff , 0xfd, 0x1e},{0xff , 0xfd, 0x1d}}; // server side
char buff2[][3] = {{0xff,0xfc,0x1e},{0xff , 0xfc, 0x1d},{0xff , 0xfc, 0x18}}; // client side

当从服务器发送三个字符中的每一个时,我收到相应的顺序响应 客户。我想知道,如果存储的缓冲区大小可变,应该进行哪些更改。 也就是说,如果 buff1[0][0] 是 0xff,0xfd,0x18,0xff,0xfd,0x21,我仍然希望将消息分成 3 部分。 这是我需要的流程:

Server Sends ---> 0xff 0xfd 0x18
Client Responds ---->0xff 0xfc 0x18

Server sends ---> 0xff 0xfd 0x21
Client Responds ---> 0xff 0xfc 0x21

我还尝试使用套接字编程发送这些缓冲区,但在发送前三个缓冲区后我得到了一个空的 recbuff。以下是我的代码:

//client
#include <stdio.h>
#include <stdlib.h>     
#include <string.h>
#include <string>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/telnet.h>
#include <unistd.h>
#include <netdb.h>

char buff2[][3] = {{0xff,0xfc,0x1e},{0xff , 0xfc, 0x1d},{0xff , 0xfc, 0x18}};

void read (int sock)
{
    char buffer[256];

    /* Now read server response */
    memset(buffer, 0, sizeof(buffer));
    int n = recv( sock, buffer, 255, 0 );
    if (n < 0) 
    {
         perror("ERROR reading from socket");
         return;
    }
    printf("\n%d bytes received buffer is: %s", n, buffer);

}

void mwrite (int sock, char * buf, int size)
{
    int n = send( sock, buf, size, 0 );
    if (n < 0) 
    {
         perror("ERROR writing to socket");
         return;
    }
    printf("Bytes Sent: %d\n", n);
  }


int main(int argc, char *argv[])
 {
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server1;

   char buffer1[256];

   if (argc < 3)
    {
        fprintf(stderr,"usage %s hostname port\n", argv[0]);
        return(0);
    }
    portno = atoi(argv[2]);
    /* Create a socket point */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);

   if (sockfd < 0) 
    {
        perror("ERROR opening socket");
        return(1);
    }

    server1 = gethostbyname(argv[1]);
    if (server1 == NULL)
    {
     fprintf(stderr,"ERROR no such host \n");
     exit(0);
    }

    bzero((char *) &serv_addr , sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server1->h_addr, (char*)&serv_addr.sin_addr.s_addr, server1->h_length);
    serv_addr.sin_port = htons( portno );


/*Connect to server*/
 if (connect( sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr) ) < 0) 
    {
         perror("ERROR connecting");
         return(1);
    }    
   printf("Recieving Buffer 1 from Server side"); 
    bzero(buffer1,256);
int i =0;

while(i <  5)
{
    n= read(sockfd,buffer1,sizeof(buffer1));
    if(n<0)
    printf("ERROR reading in socket %d  len %d", n, sizeof(buffer1));

    n= write(sockfd,buff2,sizeof(buff2));
    if(n<0)
    printf("ERROR writing in socket %d  len %d", n, sizeof(buff2));
        printf("\nSent Buffer2 (WON'T TERMINAL TYPE) from client side");
    i++;
}

return(0);
}

服务器端:

//a simple echo server

#include <stdio.h>
#include <stdlib.h>     
#include <string.h>
#include <string>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/telnet.h>
#include <unistd.h>

char buff1[][3]= {{0xff , 0xfd, 0x18},{0xff , 0xfd, 0x1e},{0xff , 0xfd, 0x1d}};

char recbuf[1024];

void mwrite (int sock, char * buf, int size)
{
    int n = send( sock, buf, size, 0 );
    if (n < 0) 
    {
         perror("ERROR writing to socket");
         return;
    }

}


void read (int sock)
{
    char buffer[256];

    /* Now read client response */
    memset(buffer, 0, sizeof(buffer));
    int n = recv( sock, buffer, 255, 0 );
    if (n < 0) 
    {
         perror("ERROR reading from socket");
         return;
    }
    for (int i = 0; i < n; i++)
         printf("%2x ", buffer[i]);//printing ascii characters
    printf("\n");
}


int main(int argc , char *argv[] )
{
  int sockfd , newsockfd , portno;
  socklen_t clilen;
  char buffer[256];
  struct sockaddr_in serv_addr, cli_addr;
  int n;

  sockfd = socket(AF_INET , SOCK_STREAM , 0);
  if (sockfd < 0 )
  {
   perror("Error opening socket ");
   exit(1);
  }

  /* Initialize socket structure */
  bzero((char *) &serv_addr , sizeof(serv_addr));
  portno = atoi(argv[1]);
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY ; 
  serv_addr.sin_port = htons(portno);

 /* Now bind the host address using client */
  if(bind(sockfd, (struct sockaddr *) &serv_addr , sizeof(serv_addr)) <0)

  { 
   perror("Error on binding");
   exit(1);
  } 


    if(listen(sockfd,5)<0)
     {
       perror("Error on listen");
       exit(1);
     }
       int k = 1;
       int count = 1;
        clilen = sizeof(cli_addr);
    newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);

    if (newsockfd < 0)
    {
     perror("ERROR on accept");
     exit(1);
    }

     printf("Server Sending (DO TERMINAL TYPE)\n");
         while(1)
         {int i = 0;
          while ((n = write(newsockfd,buff1,sizeof(buff1)))>0)
           {
           printf("Server Sent query to Client %d:%hhX %hhX %hhX\n", k , buff1[count][0], buff1[count][1], buff1[count][2]);
           n = read(newsockfd, recbuf , sizeof(recbuf));
                   printf("Value of n:%d\n",n);
                   printf("Size of RecBuf:%d\n",sizeof(recbuf));
           printf("Server received response from Client: %hhX %hhX %hhX\n\n", recbuf[i+0], recbuf[i+1], recbuf[i+2]);
                   i = i+3 ;  
           k++;
           count = k % 3;

            }
           if(n < 0)
                {
                    perror("Error writing to socket"); 
                    exit(1);
                   }

         }


      close(sockfd);
      return(0);



}

输出:

Client Side :
./single_client 127.0.0.1 5000
Recieving Buffer 1 from Server side
Sent Buffer2 (WON'T TERMINAL TYPE) from client side
Sent Buffer2 (WON'T TERMINAL TYPE) from client side
Sent Buffer2 (WON'T TERMINAL TYPE) from client side
Sent Buffer2 (WON'T TERMINAL TYPE) from client side
Sent Buffer2 (WON'T TERMINAL TYPE) from client side

Server Side :
./single_sample 5000
Server Sending (DO TERMINAL TYPE)
Server Sent query to Client 1:FF FD 1E
Value of n:9
Size of RecBuf:1024
Server received response from Client: FF FC 1E

Server Sent query to Client 2:FF FD 1D
Value of n:9
Size of RecBuf:1024
Server received response from Client: FF FC 1D

Server Sent query to Client 3:FF FD 18
Value of n:9
Size of RecBuf:1024
Server received response from Client: FF FC 18

Server Sent query to Client 4:FF FD 1E
Value of n:9
Size of RecBuf:1024
Server received response from Client: 0 0 0 // want FF FC 1E

Server Sent query to Client 5:FF FD 1D
Value of n:9
Size of RecBuf:1024
Server received response from Client: 0 0 0  // should get FF FC 1D

Server Sent query to Client 6:FF FD 18
Value of n:-1
Size of RecBuf:1024
Server received response from Client: 0 0 0  // should get  FF FC 18

基本上在来自客户端的响应中,我对所有回复都有 0xff 和 0xfc 常量,唯一的区别是第三个字符根据服务器的请求而变化。提前致谢

最佳答案

你的程序有很多问题。

首先,在两种尺寸中,您都使用:

n = write(newsockfd,buff1,sizeof(buff1))

也就是说,在每次写入时,您发送 9 个字符,当您说您只想发送 3 个

为了更难理解发生了什么,您在控制台上写的不是您发送的内容,而是您应该发送的内容

所以首先正确发送你说要发送的 3 个字符(对于服务器):

n = write(newsockfd, buff1[count], 3);

请展示你做了什么!

完成后,像测试客户端一样测试服务器端的参数(不太难......),并显示客户端发生的情况。

最后,你应该尝试使用graceful shutdown最后还是你的程序,但我必须承认这是对套接字的更高级使用

关于c - 如何使用套接字编程一次发送三个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26512202/

相关文章:

c - 对 switch 语句使用不同的语法时,优化是否有任何可能的变化?

c - C 中返回结构表的函数

c# - 在一定时间后没有收到数据时断开套接字

python - python中的套接字编程 - 时间戳

c++ - 处理套接字断开连接。 boost/Winsock

c++ - 我在哪里可以找到 NS2 库的 cpp 文件中生成的打印信息,其中我添加了一些 cout() 函数来打印一些信息?

c - 十进制转换为基数 2-16(二进制到十六进制)

服务器可以直接连接它所连接的两个套接字吗?

c++ - recv() 失败 : Bad file descriptor c++ Linux

C 数字代码验证器