ofstream not outputting when I don't have a endl c++ - c++

I have a client/server socket program that writes packets of file data in a char[2048], I've made 100% sure to null terminate all of the arrays before sending over the socket.
However on the server side I can't get the ofstream to output to the file if I do not have an endl, however this endl inserts itself at the end of the packets and makes the file have newlines in them where I don't want them to.
Here is what should be the relevant code
client
void Copy(char *filename1,string filename2,int Sockfd) {
const int BUFSIZE=2048;
char buffer[BUFSIZE];
ifstream fin;
long filelen, bytesRemaining, bytes;
// Open the file to be transferred, check it exists.
fin.open( filename1);
if (!fin.good()) {
cerr << "Problems opening \"" << filename1 << "\" (" << errno << "): " << strerror(errno) << endl;
exit(1);
}
// Determine the file's length.
fin.seekg(0,ios::end);
if(fin.fail()) cerr<<"seekg() fail!\n";
filelen = fin.tellg();
if(fin.fail()) cerr<<"tellg() fail!\n";
fin.seekg(0, ios::beg);
if(fin.fail()) cerr<<"seekg() fail!\n";
// Copy the file data.
bytesRemaining = filelen;
while (bytesRemaining > 0)
{
bytes = bytesRemaining > BUFSIZE ? BUFSIZE : bytesRemaining;
buffer[bytes] = '\0';
fin.read(buffer,bytes);
if(fin.fail())
{
cerr<<"read() errror\n";
exit(1);
}
send(Sockfd,buffer,sizeof buffer,0);
recv(Sockfd,buffer,strlen(buffer),0);
bytesRemaining -= bytes;
}
fin.close();
}
And Server
int retval;
char EchoBuffer[RCVBUFSIZE]; // Buffer for echo string
int RecvMsgSize; // Size of received message
std::ofstream fout;
fout.open("test.txt",std::ios::ate);
// Send received string and receive again until end of transmission
while(RecvMsgSize > 0)
{ // zero indicates end of transmission
// Echo message back to client
if(send(ClntSocket, EchoBuffer, RecvMsgSize, 0) != RecvMsgSize){
perror("send() failed"); exit(1);
}
// See if there is more data to receive
if((RecvMsgSize = recv(ClntSocket, EchoBuffer, RCVBUFSIZE-1, 0)) < 0){
perror("recv() failed"); exit(1);
}
EchoBuffer[RecvMsgSize] = '\0';
fout << EchoBuffer << endl; //If I don't have this endl, it won't work at all
}
fout.close();
close(ClntSocket); // Close client socket
}

You should write fout.flush(); after fout << EchoBuffer;.

Related

Unable to send the message again using C socket

I have created a ClientSocket and a ServerSocket class for simplifying functions. while sending a data, at first I am sending a 16 bytes header containing the message length followed by the message. But I am having trouble while sending data from client to server on the 2nd time. At first it is sending the header and the message properly but after that I am getting 0 bytes output from read() in ServerSocket::get_message while reading the header from the client. Please help me out here.
Sending and receiving part in Server.cpp
string ServerSocket::get_message(int client_socket_fd) {
//char *header = client_buffers[client_socket_fd].read_header;
char *read_buffer = client_buffers[client_socket_fd].read_buffer;
char header[16];
memset(header, 0, sizeof(header));
int read_result = -1;
read_result = read(client_socket_fd, header, 16);
cout << read_result << endl;
if (read_result > 0){
int read_size = stoi(string(header));
cout << read_size << endl;
memset(read_buffer, 0, sizeof(read_buffer));
read_result = read(client_socket_fd, read_buffer,read_size);
if (read_result > 0) return string(read_buffer);
}
cerr << "Unable to recieve message from client socket " << client_socket_fd << endl;
return "";
}
int ServerSocket::_send(int client_socket_fd, string message) {
//char *header = client_buffers[client_socket_fd].write_header;
char *write_buffer = client_buffers[client_socket_fd].write_buffer;
char header[16];
memset(header, 0, sizeof(header));
string write_size = to_string(message.length());
copy(write_size.begin(), write_size.end(), header);
int write_result = write(client_socket_fd, header, 16); // sending size of message
if (write_result > 0) {
write_result = write(client_socket_fd, message.c_str(), message.length());
}
if (write_result <= 0)
cerr << "Unable to send to client socket fd : " << client_socket_fd << endl;
return write_result;
}
Sending and receiving part in Client.cpp
string ClientSocket::_recieve(){
char read_header[16];
memset(read_header, 0, sizeof(read_header));
int read_result = read(socket_fd, read_header, 16);
if (read_result >0) {
int read_size = stoi(string(read_header));
memset(recieve_buffer, 0, sizeof(recieve_buffer));
read_result = read(socket_fd, recieve_buffer, read_size);
}
if ( read_result > 0) return string(recieve_buffer);
cerr << "Unable to read from server." << endl;
return "";
}
int ClientSocket::_send(string message) {
char write_header[16];
memset(write_header, 0, sizeof(write_header));
cout << message.length() << endl;
string s = to_string(message.length());
copy(s.begin(),s.end(), write_header);
int write_result = write(socket_fd, write_header, 16);
if (write_result > 0)
write_result = write(socket_fd, message.c_str(), message.length());
if (write_result <=0) cerr << "Unable to send message : "<< message << endl;
return write_result;
}
The code exhibits the two most frequent errors when using sockets:
Socket send/write and recv/read may not send/receive the number of bytes requested. The code must handle partial reads/writes in order to work correctly.
The received socket data is not zero-terminated. You need to zero-terminate the received data before passing it to functions that expect zero-terminated stings (std::string and stoi here). memset doesn't help when recv fills the entire buffer, you need to reserve one extra byte for the null terminator that recv doesn't overwrite.

Sending files over TCP using C++, recving wrong size

I am very new to socket programming, and i am trying to send over TCP connection but getting few errors.
here is my code
FILE* File;
char* Buffer;
unsigned long Size;
File = fopen("C:\\test.zip", "rb");
if (!File)
{
printf("Error while readaing the file\n");
return;
}
// file size 1
fseek(File, 0, SEEK_END);
Size = ftell(File);
fseek(File, 0, SEEK_SET);
Buffer = new char[Size];
fread(Buffer, Size, 1, File);
char cSize[MAX_PATH];
sprintf(cSize, "%i", Size);
cout << "MAX PATH " << MAX_PATH<<endl;
cout << "cSize: " << cSize << endl;
fclose(File);
`
So this to find the size of my file. most of the code i am trying it out from other questions in here but it didnt solve my problem.
'
my send and recv:
unsigned long filechunk = 1025;
unsigned long byteSent = 0;
unsigned long bytesToSend = 0;
send(Sub, cSize, MAX_PATH, 0); // File size to client
while (byteSent < Size) {
if ((Size - byteSent) >= filechunk) {
bytesToSend = filechunk;
}
else {
bytesToSend = Size - byteSent;
}
if (send(Sub, Buffer + byteSent, bytesToSend, 0)) {
std::cout << "Sent: ";
}
byteSent += bytesToSend;
std::cout << "Size : "<<Size<<" BytesSent : "<<byteSent<<" Bytes to send: " << bytesToSend << std::endl;
system("pause");
on the client side:
int Size;
char* Filesize = new char[5000000]; // is there a better way? my sfiles size are unknown but at least 50mb
if (recv(Socket, Filesize, 5000000, 0)) // File size
{
Size = atoi((const char*)Filesize);
printf("File size: %d\n", Size);
}
char* Buffer = new char[Size];
FILE* File;
File = fopen("test.zip", "wb"); //start copying from the server, creating the file first.
std::string convert;
long conv;
std::cout << "Size: " << Size << std::endl;
int total=Size;
int byteRecv = 0;
int recvCheck;
int bytes = 1025;
//getting the file
while (byteRecv < Size ) {
recvCheck = recv(Socket, Buffer, bytes, 0);
if (recvCheck >0) // File
{
fwrite(Buffer, 1, byteRecv, File);
std::cout << "Recieved:" << byteRecv << std::endl;
Size -= byteRecv;
byteRecv += byteRecv;
std::cout << "Error: " << WSAGetLastError();
}
else {
std::cout << "Error: " << WSAGetLastError();
total += 1; // the loop often get into infinit loop so i force it in case of this error.
if (total > 3) {
break;
}
}
}
fclose(File);
So, i know it is not very efficient and i am not sure if there are similar questions as i have been digging in here for a few weeks now.
-is there a better way i can make a char*[]? as i dont know the size of the files i want to send yet.
- does ftell() and sifeof() work the same way?
-when i check for the size i recved from the server it is alays wrong. Ex: server file: 32633513, recv size: 3263
-most of the code i have taken from other problems and combined it. if you see anything that is not needed do tell me so i take notes of that.
There is a lot of wrong things but that may correct your problem at first:
On the client side replace (your are both decrementing the total count of bytes and the received ones with the wrong value):
Size -= byteRecv;
byteRecv += byteRecv;
with:
byteRecv += recvCheck; // actualizes the count of received bytes
The other problem is your buffer size. Never try to get an entire file in memory, this is nonsense in general; files are usually managed chunks by chunks. As you are reading at most 1025 bytes in each loop, then only use a buffer of size 1025, you don't need more. Same for reading and writing...

changing the order of the data inside of a file using seekg, tellg function

I'm new to c++ programming. I have a small excercise which enables the use of the following: using of windows socket programming, using of window api functions (CreateFile, ReadFile, and WriteFile), and using of seekg, seekp, tellg, and tellp functions.
Here's what's happening in my code,
Open a .txt file that has URLs inside (reddit.com,stackoverflow.com,google.com) and then read the URLs and put inside of strVal.
Then I split the value of the data inside of strVal using delimiter "," then the loop starts.
Then the windows socket programming will start.
Inside of the loop it will get the HTTP request of each URLs and will ask the request type(POST or GET).
Once the answer from the request was received, the data will be inside of Buffer.
Then I will open a .txt file to put the received request of the 3 domains.
Example here's the result of output.txt
The result is fine and the program is working on this part but for the last requirement of the program, they want me to change the order of the answered data inside of the .txt file using seekg, seekp, tellg, and tellp.
I tried to implement those functions and here's my code.
fstream fs0 ("C:\\Documents and Settings\\Administrator\\My Documents\\output.txt", ios::in | ios::out | ios::app);
ofstream fs1 ("C:\\Documents and Settings\\Administrator\\My Documents\\output1.txt", ios::out | ios::app);
//1st
fs0.seekg(2020, ios::beg);
char ab[2020];
fs0.read(ab, sizeof(ab));
//2nd
fs0.seekg(0, ios::cur);
char dc[2020];
fs0.read(dc, sizeof(dc));
//3rd
fs0.seekg(0, ios::beg);
char abc[2000];
fs0.read(abc, sizeof(abc));
fs1.write(ab, sizeof(ab));
fs1.write(dc, sizeof(dc));
fs1.write(abc, sizeof(abc));
fs0.close();
fs1.close()
I just opened .txt file where the data inserted then just read the data using seekg then put it inside of a buffer then output. There's no sense because what if there's another domain inserted inside of the .txt file.
Now, my concern is on this part. Based on my code how can I change the order of the data inside of the txt file using seekg, seekp, tellg, and tellp?
Here's my overall code,
int main()
{
//getting the data
HANDLE openFile;
//HANDLE openFile1;
HANDLE putdataFile;
BOOL rewriFile;
//BOOL rewriFile1;
char *strVal;
//char *strVal1;
char* point;
//char* point1;
DWORD dwNoBytetoRead = 0;
//DWORD dwNoBytetoRead1 = 0;
DWORD dwNoByteWritten = 0;
char dataextracted[] = "C:\\Documents and Settings\\Administrator\\My Documents";
//40 dash
string dash1 = "\n--------------------";
string dash2 = "--------------------\n";
//connecting to the server
SOCKET Socket;
SOCKADDR_IN SockAddr;
struct hostent *host;
char buffer[10000];
int dataLen;
int i = 0;
//get
string http1 = "GET / HTTP/1.1\r\nHost: ";
string http2 = "\r\nConnection: close\r\n\r\n";
//post
string http3 = "POST / HTTP/1.1\r\nHost: ";
string http4 = "\r\nConnection: close\r\n\r\n";
//winsock startup
WSAData wsaData;
//1 or 2
string input;
//start of program.................................
//open file
openFile = CreateFile(L"C:\\Documents and Settings\\Administrator\\My Documents\\url.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
//allocating memory
LARGE_INTEGER fs;
GetFileSizeEx(openFile, &fs);
unsigned long long fSize = fs.QuadPart;
strVal = (char*) malloc (fSize + 1);
memset(strVal, 0, fSize + 1);
//reading the content
rewriFile = ReadFile(openFile, strVal, fSize, &dwNoBytetoRead, NULL);
cout << "The URL/s " << strVal << endl << endl;
CloseHandle(openFile);
//split string
point = strtok(strVal, ",\r\n");
while (point != NULL) {
//get
string httpRequestget = http1 + point + http2;
//post
string httpRequestpost = http3 + point + http4;
//checking kung successful yung wsastartup
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
//return 1;
}
//connects to domain
Socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
host = gethostbyname(point);
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
//just to check kung connected or may error pala
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
cout << "Could not connect";
system("pause");
//return 1;
}else{
cout << "You are now connected to " << point << endl;
}
//choice 1 or 2
cout << "Options to request\n";
cout << "[1] HTTP request using GET\n";
cout << "[2] HTTP request using POST\n";
cout << "Choose an option: ";
cin >> input;
cout << endl;
if (input == "1"){
// Sending a HTTP-GET-Request to the Web Server
int sentBytes = send(Socket, httpRequestget.c_str(), strlen(httpRequestget.c_str()),0);
} else if (input == "2") {
// Sending a HTTP-POST-Request to the Web Server
int sentBytes = send(Socket, httpRequestpost.c_str(), strlen(httpRequestpost.c_str()),0);
}
// Receiving and Displaying an answer from the Web Server
ZeroMemory(buffer, sizeof(buffer));
recv(Socket, buffer, sizeof(buffer), 0);
//put data in a file
putdataFile = CreateFile(L"C:\\Documents and Settings\\Administrator\\My Documents\\output.txt", FILE_APPEND_DATA, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
string dash3 = dash1 + point + dash2;
//write dash
rewriFile = WriteFile(putdataFile, dash3.c_str(), strlen(dash3.c_str()), &dwNoByteWritten, NULL);
//write the content
rewriFile = WriteFile(putdataFile, buffer, 2000, &dwNoByteWritten, NULL);
CloseHandle(putdataFile);
// Cleaning up Windows Socket Dependencies
closesocket(Socket);
WSACleanup();
point = strtok(NULL, ",\r\n");
}
cout << endl << "Data is downloaded here: " << dataextracted << endl << endl;
fstream fs0 ("C:\\Documents and Settings\\Administrator\\My Documents\\output.txt", ios::in | ios::out | ios::app);
ofstream fs1 ("C:\\Documents and Settings\\Administrator\\My Documents\\output1.txt", ios::out | ios::app);
//1st
fs0.seekg(2020, ios::beg);
char ab[2020];
fs0.read(ab, sizeof(ab));
//2nd
fs0.seekg(0, ios::cur);
char dc[2020];
fs0.read(dc, sizeof(dc));
//3rd
fs0.seekg(0, ios::beg);
char abc[2000];
fs0.read(abc, sizeof(abc));
fs1.write(ab, sizeof(ab));
fs1.write(dc, sizeof(dc));
fs1.write(abc, sizeof(abc));
fs0.close();
fs1.close();
system("pause");l
return 0;
}

Sending Picture via TCP

I'm trying to send a jpg file from a client to a server using TCP. When the picture arrives to the server side I can't open it, besides the size of the picture received is higher than the one sent (sent = 880 bytes , received = 894 bytes). Any one of you have an idea of how to do solve this problem ? Here is my code :
client code :
static int send_server_image(SOCKET sock){
int n = 0;
int siz = 0;
FILE *picture;
char buf[50];
char *s="";
cout << "Getting image size" << endl;
picture = fopen("C:\\Users\\n.b\\Desktop\\c++\\TCP\\tcp_client_image_pp\\test.jpg", "r");
fseek(picture, 0, SEEK_END);
siz = ftell(picture);
cout << siz << endl; // Output 880
cout << "Sending picture size to the server" << endl;
sprintf(buf, "%d", siz);
if((n = send(sock, buf, sizeof(buf), 0)) < 0)
{
perror("send_size()");
exit(errno);
}
char Sbuf[siz];
cout << "Sending the picture as byte array" << endl;
fseek(picture, 0, SEEK_END);
siz = ftell(picture);
fseek(picture, 0, SEEK_SET); //Going to the beginning of the file
while(!feof(picture)){
fread(Sbuf, sizeof(char), sizeof(Sbuf), picture);
if((n = send(sock, Sbuf, sizeof(Sbuf), 0)) < 0)
{
perror("send_size()");
exit(errno);
}
memset(Sbuf, 0, sizeof(Sbuf));
}
}
server code :
static int recv_client_image(SOCKET sock){
int n = 0;
cout << "Reading image size" << endl;
char buf[50];
int siz = 0;
if ((n = recv(sock, buf, sizeof(buf), 0) <0)){
perror("recv_size()");
exit(errno);
}
siz = atoi(buf);
cout << siz << endl; // 880 output
char Rbuffer[siz];
cout << "Reading image byte array" << endl;
n = 0;
if ((n = recv(sock, Rbuffer, sizeof(Rbuffer), 0)) < 0){
perror("recv_size()");
exit(errno);
}
cout << "Converting byte array to image" << endl;
FILE *image;
image = fopen("recu.jpg", "w");
fwrite(Rbuffer, sizeof(char), sizeof(Rbuffer), image);
fclose(image);
cout << "done" << endl;
}
Thank you.
You are using Variable Length Arrays, which is not standard C++ (ref). Even if it is accepted by your compiler, you should avoid using sizeof on that.
And you have a problem in the while(!feof(picture)). You read siz bytes from the file without any error and without setting the eof flag. On second read, you read 0 bytes and set the flag but also send another buffer.
You should write instead:
while(!feof(picture)){
n = fread(Sbuf, sizeof(char), siz, picture);
if (n > 0) { /* only send what has been read */
if((n = send(sock, Sbuf, siz, 0)) < 0) /* or (better?) send(sock, Sbuf, n, 0) */
{
perror("send_data()");
exit(errno);
}
}
/* memset(Sbuf, 0, sizeof(Sbuf)); useless for binary data */
}
Same in server part:
if ((n = recv(sock, Rbuffer, siz, 0)) < 0){
perror("recv_size()");
exit(errno);
}
cout << "Converting byte array to image" << endl;
FILE *image;
image = fopen("recu.jpg", "w");
fwrite(Rbuffer, sizeof(char), siz, image);
fclose(image);
And there is a last possibility of error, at least if you are on a platform that makes a difference between text and binary file like Windows is that you forget to open the files in binary mode, which could break the jpg image. Because on windows for a binary file, byte 0x10 is seen as the new line (\n') and written as 2 bytes 0x0d 0x10 (\r\n).
So you must open the input file in rb mode and the output file in wb mode.
Solved :
All the correction that Serge Ballesta were right. But the problem was in the way I was opening my files.
You need to open the file in binary mode ("rb" for reading, "wb" for writing), not the default text mode.
Client :
picture = fopen("C:\\Users\\n.b\\Desktop\\c++\\TCP\\tcp_client_image_pp\\test.jpg", "rb");
Server :
image = fopen("recu.jpg", "wb");
That was the main problem. Thank you.

GET and PUT commands with C++ Server-Client

I'm trying to create a server, client put and get method but I don't really know where to start, how do I make the server run the commands I process. Any help would be much appreciated.
Client file
void Copy(char *filename1,char *filename2);
int main(int argc, char **argv)
{
if(argc == 3)
{
int Sockfd;
sockaddr_in ServAddr;
hostent *HostPtr;
int Port = atoi(argv[2]);
int BuffSize = 0;
// get the address of the host
HostPtr = Gethostbyname(argv[1]);
if(HostPtr->h_addrtype != AF_INET)
{
perror("Unknown address type!");
exit(1);
}
memset((char *) &ServAddr, 0, sizeof(ServAddr));
ServAddr.sin_family = AF_INET;
ServAddr.sin_addr.s_addr = ((in_addr*)HostPtr->h_addr_list[0])->s_addr;
ServAddr.sin_port = htons(Port);
// open a TCP socket
Sockfd = Socket(AF_INET, SOCK_STREAM, 0);
// connect to the server
Connect(Sockfd, (sockaddr*)&ServAddr, sizeof(ServAddr));
char userI[256];
// write a message to the server
int dupSockfd = dup(Sockfd);
FILE* writeFile = fdopen(Sockfd, "w");
FILE* readFile = fdopen(dupSockfd, "r");
setlinebuf(writeFile);
char writerBuff[256];
for(;;)
{
cout << "ftp> ";
if(fgets(userI, sizeof(userI), stdin))
{
if(userI == "exit")
{
return 1;
}
else
{
string cmd, f1, f2;
istringstream iss(userI, istringstream::in);
iss >> cmd >> f1 >> f2;
cout << cmd << "." << f1 << "." << f2 << endl;
if(cmd == "get")
{
write(Sockfd, "get", sizeof("get"));
Copy(f1, f2);
}
}
}
}
close(Sockfd);
}
else
{
cout << "Incorrect commands for running... try './client (hostname) (port)'" << endl;
return 1;//
}
return 0;//
}
void Copy(char *filename1,char *filename2) {
const int BUFSIZE=2048;
char buffer[BUFSIZE];
ifstream fin;
ofstream fout;
long filelen, bytesRemaining, bytes;
// Open the file to be transferred, check it exists.
fin.open( filename1);
if (!fin.good())
{
cerr << "Problems opening \"" << filename1 << "\" (" << errno << "): " << strerror(errno) << endl;
exit(1);
}
fout.open(filename2);
if (!fout.good())
{
cerr << "Problems opening \"" << filename2 << "\" (" << errno << "): " << strerror(errno) << endl;
exit(1);
}
// Determine the file's length.
fin.seekg(0,ios::end);
if(fin.fail()) cerr<<"seekg() fail!\n";
filelen = fin.tellg();
if(fin.fail()) cerr<<"tellg() fail!\n";
fin.seekg(0, ios::beg);
if(fin.fail()) cerr<<"seekg() fail!\n";
// Copy the file data.
bytesRemaining = filelen;
while (bytesRemaining > 0)
{
bytes = bytesRemaining > BUFSIZE ? BUFSIZE : bytesRemaining;
fin.read(buffer,bytes);
if(fin.fail()){
cerr<<"read() error\n";
exit(1);
}
fout.write(buffer,bytes);
if(fout.fail()){
cerr<<"write() error\n";
exit(1);
}
bytesRemaining -= bytes;
}
fin.close();
fout.close();
}
Server file
int main(int argc, char **argv)
{
if(argc == 2)
{
int Sockfd, NewSockfd, ClntLen;
sockaddr_in ClntAddr, ServAddr;
int Port = atoi(argv[1]);
char String[MAX_SIZE];
int Len;
// open a TCP socket (an Internet stream socket)
Sockfd = Socket(AF_INET, SOCK_STREAM, 0); // socket() wrapper fn
// bind the local address, so that the client can send to server
memset((char*)&ServAddr, 0, sizeof(ServAddr));
ServAddr.sin_family = AF_INET;
ServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
ServAddr.sin_port = htons(Port);
int opt = 1;
setsockopt(Sockfd,SOL_SOCKET,SO_REUSEADDR, (void*)opt, sizeof(opt));
Bind(Sockfd, (sockaddr*) &ServAddr, sizeof(ServAddr));
// listen to the socket
Listen(Sockfd, 5);
int RecvMsgSize;
for(;;)
{
// wait for a connection from a client; this is an iterative server
ClntLen = sizeof(ClntAddr);
NewSockfd = Accept(Sockfd, (sockaddr*)&ClntAddr, &ClntLen);
if((RecvMsgSize = recv(ClntSocket, EchoBuffer, RCVBUFSIZE, 0)) < 0)
{
perror("recv() failed");
exit(1);
}
// read a message from the client
Len = read(NewSockfd, String, MAX_SIZE);
String[Len] = 0;// make sure it's a proper string
cout<< String << endl;
close(NewSockfd);
}
}
else
{
cout << "Incorrect commands for running... try './server (port)'" << endl;
return 1;//
}
return 0;//
}
You want to create a Web server that will process GET and PUT requests? You first need to read how the http works. Let me explain in simple terms.
Try to develop your server first and connect it to a browser :
1.Make your server listen on port 80 - this is a must
2.Create a buffer that will read the request from the browser(client), as you do in this part of your code:
if((RecvMsgSize = recv(ClntSocket, EchoBuffer, RCVBUFSIZE, 0)) < 0)
{
perror("recv() failed");
exit(1);
}
// read a message from the client
Len = read(NewSockfd, String, MAX_SIZE);
String[Len] = 0;// make sure it's a proper string
cout<< String << endl;
close(NewSockfd);
so this String object is your buffer, it will contain the http request.
3.You need to parse the request. Parse the request to see whether the method is GET PUT POST or etc.
This is a sample GET request :
https://marketing.adobe.com/developer/documentation/data-insertion/r-sample-http-get
4.Then you need to send the proper response back to the client in this case the browser:
http://pastebin.com/BPnVHym5
5.Connect your browser to the server by typing your ip adress in the addressbar
I would honestly use a C++ REST API library to do the work. You can find one called "Casablanca."
Here's an example on how to use it for making a client: https://casablanca.codeplex.com/wikipage?title=Http%20Client%20Tutorial
Here is an example on how to create a server: https://casablanca.codeplex.com/wikipage?title=HTTP%20Listener&referringTitle=Documentation
Maybe this will get you started.