如何通过套接字从服务器向客户端发送文本文件的内容?

时间:2018-10-31 22:31:29

标签: c++ c sockets server client

我正在做一个分配,允许服务器通过I / O重定向获取文本文件的内容,并逐行发送到客户端,然后将其插入向量中。我已经尝试在两边都使用while循环,但是没有用。它仅读取文件的第一行(为了获得第一大小,我分别进行了此操作)。有人可以建议我如何解决此问题吗?

这是我的服务器代码:

listen(sockfd,5);
 clilen = sizeof(cli_addr);
 newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t *)&clilen);

 if (newsockfd < 0){ 
      error("ERROR on accept");
 }
 bzero(buffer,256);
 n = read(newsockfd,buffer,255);

 if (n < 0){
     error("ERROR reading from socket");
 }

 printf("Here is the message: %s\n",buffer);
 std::getline(std::cin, getFile); // I/O Redirection
 n = write(newsockfd,getFile.c_str(),18); //grabs first line of the file which is 3 and sends it to the client

 while (std::getline(std::cin, getFile)) { 
     n = write(newsockfd, getFile.c_str(), 18); //supposed to write every line of the file to the client but isn't working? Should send 0 1 0 0 1 0 1 -1
     if (n < 0){
         error("ERROR writing to socket");
     }
 }

我的客户代码:

std::vector<int> input;

printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));

if (n < 0) {
    error("ERROR writing to socket");
}

printf("The ring size is: ");
bzero(buffer,256);
n = read(sockfd,buffer,255); //received first line from server
size = std::atoi(buffer); //ring size converted from char* to int

while (read(sockfd, buffer, 255) > 0) {
    input.push_back(std::atoi(buffer));
    printf("Input contents: %s\n", buffer); //should print 0 1 0 0 1 0 1 -1
}

我的文本文件:

3
0
1
0
0
1
0
1
-1

1 个答案:

答案 0 :(得分:2)

TCP是基于流的协议,而不是基于消息的协议。这意味着,如果要将单个消息作为单个消息处理,则需要建立一个协议来分隔单个消息。 read(sockfd, buffer, 255)可以轻松地从套接字中读取255个字节的数据,其中包含多条消息,甚至可能是整个文件,但程序仅将其视为一条消息。

This answer contains a relatively simple protocol for sending strings over a socket