函数read_and_send没有被调用,没有错误消息。基本上我想要做的是我想在并发服务器和客户端程序之间进行通信。客户端将请求一个文件,服务器将检查该文件是否可用,然后它将检查文件大小是否为< 1000字节,然后只是将文件发送给用户,但如果文件大小> = 1000字节,那么服务器将压缩它并传输到客户端。
我所做的是客户端输入文件名,服务器将file_name和communication_socket传递给一个函数(导致问题)。该函数查找文件的长度并相应地执行。
我正在使用ubuntu 13.10。任何帮助将不胜感激。 这是代码:
#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<cstring>
#include<stdlib.h>
#include<fstream>
using namespace std;
void read_and_send(char *file_name, int comm_sock);
bool compress_file(char *file, char *new_file);
int main()
{
char *msg, *data;
struct in_addr addr;
int conn_sock,comm_sock,n;
struct sockaddr_in server_addr,client_addr;
conn_sock= socket (AF_INET,SOCK_STREAM,0);
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(1234); // @
server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
bind(conn_sock,(struct sockaddr *) &server_addr,sizeof(server_addr));
listen(conn_sock,10);
while(true)
{
comm_sock = accept(conn_sock, (struct sockaddr *)&client_addr,(socklen_t *)&client_addr);
cout<<"Conection Established\n\n";
if(fork()==0)
{
while(true)
{
data=new char[100];
n= read(comm_sock,data,100);
cout<<" Data Recieved : ";
cout<<data<<endl;
if((strcmp(data,"QUIT")==0) || (strcmp(data,"quit")==0))
{
break;
}
cout<<" Input : ";
read_and_send(data, comm_sock); // not getting called
/* if I execute this (i.e: for simple communicating with text messages, then everything goes fine.
msg=new char[100];
cin.getline(msg,100,'\n');
write(comm_sock,msg,100);
*/
}
}
else
{
close(comm_sock);
}
}
delete []data;
delete []msg;
close(conn_sock);
return 0;
}
read_and_send():
void read_and_send(char *file_name, int comm_sock) //server_side
{
ifstream myReadFile;
myReadFile.open(file_name);
if(myReadFile)
{
char *output;
if (myReadFile.is_open())
{
myReadFile.seekg (0, myReadFile.end);
int length = myReadFile.tellg();
myReadFile.seekg (0, myReadFile.beg);
if(length < 1000)
{
output = new char[length];
if(!myReadFile.eof())
{
myReadFile >> output;
write(comm_sock,output,length);
}
myReadFile.close();
}
else
{
char new_file[] = "compressed.txt";
myReadFile.close();
bool is_compressed = compress_file(file_name, new_file);
ifstream f;
f.open(new_file);
if(f)
{
f.seekg (0, f.end);
int compressed_length = f.tellg();
f.seekg (0, f.beg);
output = new char[compressed_length];
if(!f.eof())
{
f >> output;
write(comm_sock,output,length);
}
}
else
cout<<"read_and_send: Error opening compressed file";
}
delete[] output; // deallocating, dynamically allocated resources
}
else
cout<<"read_and_send: Error opening file";
}
else
cout<<"read_and_send: file don't exists";
}