[英]How to send contents of a text file from server to client via sockets?
I am working on an assignment that would allow the server to grab the contents of a text file via I/O redirection and send to the client line by line which I would then insert into a vector. 我正在做一个分配,允许服务器通过I / O重定向获取文本文件的内容,然后逐行发送到客户端,然后将其插入向量中。 I have tried using a while loop on both sides, but it isn't working.
我已经尝试在两边都使用while循环,但是没有用。 It only reads the first line of the file (which I was doing separately in order to get the size first) and that's it.
它仅读取文件的第一行(为了获得第一大小,我分别进行了此操作)。 Can anyone please advise me on how to fix this issue?
谁能建议我如何解决此问题?
Here's my server code: 这是我的服务器代码:
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");
}
}
My client code: 我的客户代码:
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
}
My text file: 我的文字档:
3
0
1
0
0
1
0
1
-1
TCP is a stream-based, not a message based, protocol. TCP是基于流的协议,而不是基于消息的协议。 That means you need to establish a protocol that separates individual messages if they are intended to be processed as individual messages.
这意味着,如果要将单个消息作为单个消息处理,则需要建立一个协议来分隔单个消息。
read(sockfd, buffer, 255)
could easily read 255 bytes of data from the socket which contains multiple messages, possibly even the whole file, but the program only treats it as a single message. read(sockfd, buffer, 255)
可以轻松地从套接字读取255个字节的数据,该套接字包含多个消息,甚至可能是整个文件,但程序仅将其视为一条消息。
This answer contains a relatively simple protocol for sending strings over a socket 此答案包含一个用于通过套接字发送字符串的相对简单的协议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.