sorry I know I have been posting threads related to the same topic over throughout the past day but I've hit another issue.
server.cpp
/*Server */
#define _WIN32_WINNT 0x501
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std;
const int winsock_version = 2;
#define PORT "3490"
#define MAX_NUM_CONNECTIONS 10
int main(void){
WSADATA wsadata;
if (WSAStartup(MAKEWORD(winsock_version,0),&wsadata) == 0){
cout<<"-WSAStartup Initialized." << endl;
struct addrinfo hints,*res;
int sock_fd;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(NULL,PORT,&hints,&res) != 0){
cout<<"-Call to getaddress was unsucceful." << endl;
}
if( (sock_fd = socket(res->ai_family,res->ai_socktype,res->ai_protocol)) == -1){
cout<<"-Unable to Create socket." << endl;
}
if ( (bind(sock_fd, res->ai_addr, res->ai_addrlen)) != -1 ){
cout<<"-binding successful." << endl;
}
if ( (listen(sock_fd,MAX_NUM_CONNECTIONS)) != -1){
cout<<"-Listening for incoming connections." << endl;
}
//-------------------------------------------------------------
struct sockaddr_storage incming_info;
socklen_t sin_size;
sin_size = sizeof incming_info;
int new_fd;
new_fd = accept(sock_fd, (struct sockaddr*)&incming_info,&sin_size);
if (new_fd == -1){
cout<<"-Accepting error." << endl;
}
if(new_fd == INVALID_SOCKET){
cout<<"-INVALID SOCKET ERROR." << endl;
}
//-------------------------------------------------------------
cout<<"Connected?" << endl;
char buffer[128];
while(true){
int ret_val;
ret_val = recv(new_fd,buffer,sizeof(buffer),0);
if(ret_val == -1){
cout<<"Receiving Error." << endl;
break;
}else if(ret_val == 0){
cout<<"Connection has been closed!." << endl;
break;
}else if(ret_val > 0){
cout<<"Server: " << buffer<< endl;
}
}
cout<<"-Closing connection" << endl;
closesocket(new_fd);
}else{
cout<<"-WSAStartup Initialization failed." << endl;
if(WSACleanup()!=0){
cout<<"-WSACleanup Successful." << endl;
}else{
cout<<"-WSACleanup Failed." << endl;
}
}
return 0;
}
client.cpp
/*client*/
#define _WIN32_WINNT 0x501
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std;
#define PORT "3490"
#define SERVER "localhost"
const int winsockVersion = 2;
int main(void){
WSADATA wsadata;
if ( (WSAStartup(MAKEWORD(2,0),&wsadata)) == 0){
cout<<"-WSAStartup Initialized." << endl;
struct addrinfo hints, *res;
int sockfd;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(SERVER,PORT,&hints,&res) != 0){
cout<<"-getaddrinfo unsuccessful." << endl;
}
if ( (sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol)) == -1 ){
cout<<"-Unable to create socket." << endl;
}
if ( (connect(sockfd,res->ai_addr,res->ai_addrlen)) != -1 ){
cout<<"-Connection Established." << endl;
}
cout<<"-Client connecting to: " << res->ai_addr << endl;
while(true){
char text_buff[128];
cout<<"Enter text: ";
cin>>text_buff;
if( (send(sockfd,text_buff,sizeof(text_buff),0)) != -1 ){
cout<<"-text_buff sent!." << endl;
break;
}
closesocket(sockfd);
}
}else{
cout<<"-WSAStartup Initialization failed." << endl;
if(WSACleanup()!=0){
cout<<"-WSACleanup Successful." << endl;
}else{
cout<<"-WSACleanup Failed." << endl;
}
}
return 0;
}
I can run the server and client fine, but I can only send one word (cant send a sentence for some reason) from the client which gets printed out on the server console but as soon as it is printed out on the server console it outputs "Receiving error" and closes.
You can't assume that a single call to send() is enough (and the same for recv()). You need to loop over the data until all data has been sent/received.
Also, you very probably don't want to always send 128 characters, instead you should just send the required length (and have either a terminator or a prefixed length in the message).
Two issues
1. cin>>text_buff; is reading only till the first space. You can use std::string.
2. send(sockfd,text_buff,sizeof(text_buff),0) use strlen(text_buff) + 1 instead of sizeof(text_buff).
If using std::string, then try
string line;
send(sockfd, line.c_str(),line.length()+1,0)
Try replacing the input from using a char text_buff with a std::string and std::getline.
while( true )
{
std::string line;
std::cout << "Enter text: ";
std::getline( cin, line );
if( send( sockfd, text_buff.c_str(), text_buff.size(), 0 ) ) != -1 )
{
std::cout << "-text_buff sent!." << std::endl;
break;
}
closesocket( sockfd );
}
I am not sure about your loop there as you seem to be looping just to exit the first time you successfully send anything.
Related
I am writing for the first time in this language and could only write this
UDP server and client. I need help; I want to server waits for a response and displays it. If within 5 sec. the answer is not received, the program starts its execution again.If you don't understand task, you can translate task(fifth) :https://www.opennet.ru/docs/RUS/socket/node15.html
#include <iostream>
#include <WS2tcpip.h>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
void main()
{
struct timeval tv;
fd_set fd;
WSADATA data;
WORD version = MAKEWORD(2, 2);
int wsOk = WSAStartup(version, &data);
cout << "Server opened" << endl;
if (wsOk != 0)
{
cout << "Can't start Winsock! " << wsOk;
return;
}
SOCKET in = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in serverHint;
serverHint.sin_addr.S_un.S_addr = ADDR_ANY;
serverHint.sin_family = AF_INET;
serverHint.sin_port = htons(54000);
if (bind(in, (sockaddr*)& serverHint, sizeof(serverHint)) == SOCKET_ERROR)
{
cout << "Can't bind socket! " << WSAGetLastError() << endl;
return;
}
sockaddr_in client;
int clientLength = sizeof(client);
char buf[1024];
while (true)
{
FD_ZERO(&fd);
FD_SET(in, &fd);
tv.tv_sec = 5;
tv.tv_usec = 0;
if (select(0, &fd, NULL, NULL, &tv) > 0)
{
ZeroMemory(&client, clientLength);
ZeroMemory(buf, 1024);
int bytesIn = recvfrom(in, buf, 1024, 0, (sockaddr*)& client, &clientLength);
if (bytesIn == SOCKET_ERROR)
{
cout << "Error receiving from client " << WSAGetLastError() << endl;
continue;
}
char clientIp[256];
ZeroMemory(clientIp, 256);
inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);
cout << "Message recv from " << clientIp << " : " << buf << endl;
}
else {
cout << "Timeout" << endl;
closesocket(in);
break;
}
closesocket(in);
WSACleanup();
}
}
Translation of the task by google translate:
Write a program that asks the user for an IP address, port number and text string,
sends a string to the specified address using the UDP protocol,
waits for a response, and displays it on the screen.
If within 5 sec. the answer is not received, the program starts its execution again.
Your program is completely missing part 1 and 2 so you must add those.
For part 3, move your current while loop so it covers everything in main:
int main() // note: main must be declared to return 'int'
{
while(true) { // new start of the while loop, first in main
// ... your current code until the below line ...
cout << "Message recv from " << clientIp << " : " << buf << endl;
// exit program if you've received a response
closesocket(in);
break; // break out of while loop
}
else {
cout << "Timeout" << endl;
}
closesocket(in);
WSACleanup();
} // end of while loop
WSACleanup();
} // end of main
This reinitializer Winsock2 for every try which is unnecessary and it also has closesocket in multiple places. I would add classes for both WSAStartup/WSACleanup and socket/closesocket to manage the resources they have acquire.
#include <iostream>
#include <WS2tcpip.h>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
void main()
{
struct timeval tv;
fd_set fd;
WSADATA data;
WORD version = MAKEWORD(2, 2);
int wsOk = WSAStartup(version, &data);
cout << "5" << endl;
if (wsOk != 0)
{
cout << "Winsock" << wsOk;
return;
}
SOCKET in = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in serverHint;
serverHint.sin_addr.S_un.S_addr = ADDR_ANY;
serverHint.sin_family = AF_INET;
serverHint.sin_port = htons(54000);
if (bind(in, (sockaddr*)& serverHint, sizeof(serverHint)) == SOCKET_ERROR)
{
cout << "hhhh" << WSAGetLastError() << endl;
return;
}
sockaddr_in client;
int clientLength = sizeof(client);
char buf[1024];
while (true)
{
FD_ZERO(&fd);
FD_SET(in, &fd);
tv.tv_sec = 5;
tv.tv_usec = 0;
if (select(0, &fd, NULL, NULL, &tv) > 0)
{
ZeroMemory(&client, clientLength);
ZeroMemory(buf, 1024);
int bytesIn = recvfrom(in, buf, 1024, 0, (sockaddr*)& client, &clientLength);
if (bytesIn == SOCKET_ERROR)
{
cout << "EEEROOR" << WSAGetLastError() << endl;
continue;
}
char clientIp[256];
ZeroMemory(clientIp, 256);
inet_ntop(AF_INET, &client.sin_addr, clientIp, 256);
cout << "ะก " << clientIp << " : " << buf << endl;
closesocket(in);
WSACleanup();
exit(0);
}
else {
cout << "jhkjhkjhjn" << endl;
closesocket(in);
main();
}
}
}
The way my code is currently written only allows a message from the server to be read directly after input is taken and a message is sent. However, this code is for a chat server and must allow a read to occur at any time a message is sent.
#include <iostream>
#include <string>
#include <cstring>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVER_ADDRESS "127.0.0.1"
constexpr int server_port = 15555;
#define SERVER_SUCCESS "1"
#define SERVER_FAILURE "-1"
constexpr int msg_buffer_size = 4096;
int main(int argc, char *argv[])
{
struct sockaddr_in serv_addr;
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
std::cerr << "Socket creation failed!" << std::endl;
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(server_port);
if (inet_pton(AF_INET, SERVER_ADDRESS, &serv_addr.sin_addr) <= 0)
{
std::cerr << "Invalid server address!" << std::endl;
return 1;
}
if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
std::cerr << "Failed to connect to chat server!" << std::endl;
return 1;
}
int valread;
while (true)
{
std::cout << ">> ";
char msg[msg_buffer_size];
char return_msg[msg_buffer_size];
std::string input;
std::getline(std::cin, input);
if (input == "quit")
return 0;
if (input.length() > 4000)
{
std::cout << "Input length must be less than 4000 characters." << std::endl;
continue;
}
strcpy(msg, input.c_str());
if (send(sock, msg, strlen(msg), 0) < 0)
{
std::cout << "Error sending data." << std::endl;
continue;
}
if (recv(sock, return_msg, msg_buffer_size, 0) < 0)
{
std::cout << "Error receiving data." << std::endl;
continue;
}
std::string code(strtok(return_msg, " "));
if (code == SERVER_FAILURE)
std::cout << "Failure: " << strtok(NULL, "") << std::endl;
else
std::cout << strtok(NULL, "") << std::endl;
memset(msg, 0, msg_buffer_size);
memset(return_msg, 0, msg_buffer_size);
}
std::cout << "Exiting." << std::endl;
close(sock);
return 0;
}
What would be a correct way to allow the client to receive a message as soon as one is sent from the server? I was thinking about making a thread, but it seemed kind of redundant since I would be receiving in two places.
I have working server and client code. The server and client can connect and chat with each other correctly. But when I open another client terminal, the client is says Awaiting confirmation from the server and nothing else. Although server and client #1 can still chat.
I searched on multi-threading but the examples or code snippets they show is advanced. Maybe a little explanation or an example will help a lot!
The code below is working. I have a working server but it only accepts one connection. How do I make the server to allow multiple connection? So that I can make the program look like a group chat.
client.cpp (when client #2 connects, the code freezes at line 40)
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int main()
{
char a;
int client;
int portNum = 1500;
int bufsize = 1024;
char* buffer = new char[bufsize];
bool isExit = false;
char* ip = "127.0.0.1";
struct sockaddr_in direc;
if ((client = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
cout << "\nError creating socket..." << endl;
exit(0);
}
cout << "\nSocket created successfully..." << endl;
direc.sin_family = AF_INET;
direc.sin_port = htons(portNum);
inet_pton(AF_INET, ip, &direc.sin_addr);
if (connect(client,(struct sockaddr *)&direc, sizeof(direc)) == 0)
cout << "Connection to the server " << inet_ntoa(direc.sin_addr) << endl;
cout << "Awaiting confirmation from the server..." << endl; //line 40
recv(client, buffer, bufsize, 0);
cout << "\n=> Enter # to terminate the connection\n" << endl;
do {
cout << "Client: ";
do {
cin >> buffer;
send(client, buffer, bufsize, 0);
if (*buffer == '#') {
send(client, buffer, bufsize, 0);
*buffer = '*';
isExit = true;
}
} while (*buffer != 42);
cout << "Server: ";
do {
recv(client, buffer, bufsize, 0);
cout << buffer << " ";
if (*buffer == '#') {
*buffer = '*';
isExit = true;
}
} while (*buffer != 42);
cout << endl;
} while (!isExit);
cout << "=> Connection terminated.\nGoodbye";
close(client);
return 0;
}
server.cpp
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int main()
{
int client, server;
int bufsize = 1024;
int portNum = 1500;
bool isExit = false;
char* buffer = new char[bufsize];
struct sockaddr_in direc;
socklen_t tamano;
pid_t pid;
if ((client = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
cout << "\nError establishing socket..." << endl;
exit(1);
}
cout << "\nSocket server has been created..." << endl;
direc.sin_family = AF_INET;
direc.sin_addr.s_addr = htons(INADDR_ANY);
direc.sin_port = htons(portNum);
if ((bind(client, (struct sockaddr*)&direc,sizeof(direc))) < 0) {
cout << "\nError binding connection..." << endl;
return -1;
}
tamano = sizeof(direc);
cout << "Looking for clients..." << endl;
listen(client, 1);
while ((server = accept(client,(struct sockaddr *)&direc,&tamano)) > 0) {
strcpy(buffer, "Server connected...\n");
send(server, buffer, bufsize, 0);
cout << "Connected with the client, you are good to go..." << endl;
cout << "Enter # to end the connection\n" << endl;
cout << "Client: ";
do {
recv(server, buffer, bufsize, 0);
cout << buffer << " ";
if (*buffer == '#') {
*buffer = '*';
isExit = true;
}
} while (*buffer != '*');
do {
cout << "\nServer: ";
do {
cin >> buffer;
send(server, buffer, bufsize, 0);
if (*buffer == '#') {
send(server, buffer, bufsize, 0);
*buffer = '*';
isExit = true;
}
} while (*buffer != '*');
cout << "Client: ";
do {
recv(server, buffer, bufsize, 0);
cout << buffer << " ";
if (*buffer == '#') {
*buffer == '*';
isExit = true;
}
} while (*buffer != '*');
} while (!isExit);
cout << "\n=> Connection terminated... " << inet_ntoa(direc.sin_addr);
close(server);
cout << "\nGoodbye..." << endl;
isExit = false;
}
close(client);
return 0;
}
How do I make the server accept multiple connection?
Thanks!
In order to properly support multiple connections you should fire up a new thread for each incoming connection. Each new connection is identified by its own unique socket descriptor returned by accept(). A simple example:
while ((accepted = accept(client,(struct sockaddr *)&direc,&tamano)) > 0) {
/*Create the thread and pass the socket descriptor*/
if( pthread_create(new_thread, &thread_attributes, &handle_tcp_connection, (void *)accepted) != 0){
perror("create thread");
exit(EXIT_FAILURE);
}
}
You will need to use select or poll and a state machine pattern to do what you want to do. This means that you will need to process the data as it comes in from whichever client is sending it. Take a look here for a working example.
this is probably trivial but I need help in making my server listen on my ISP IP address rather than the localhost in my client-server messager program. My server and client is as follows.
server
/*Server */
#define _WIN32_WINNT 0x501
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std;
const int winsock_version = 2;
#define PORT "3490"
#define MAX_NUM_CONNECTIONS 10
int main(void){
WSADATA wsadata;
if (WSAStartup(MAKEWORD(winsock_version,0),&wsadata) == 0){
cout<<"-WSAStartup Initialized." << endl;
struct addrinfo hints,*res;
int sock_fd;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(NULL,PORT,&hints,&res) != 0){
cout<<"-Call to getaddress was unsucceful." << endl;
}
if( (sock_fd = socket(res->ai_family,res->ai_socktype,res->ai_protocol)) == -1){
cout<<"-Unable to Create socket." << endl;
}
if ( (bind(sock_fd, res->ai_addr, res->ai_addrlen)) != -1 ){
cout<<"-binding successful." << endl;
}
if ( (listen(sock_fd,MAX_NUM_CONNECTIONS)) != -1){
cout<<"-Listening for incoming connections." << endl;
}
//-------------------------------------------------------------
struct sockaddr_storage incming_info;
socklen_t sin_size;
sin_size = sizeof incming_info;
int new_fd;
new_fd = accept(sock_fd, (struct sockaddr*)&incming_info,&sin_size);
if (new_fd == -1){
cout<<"-Accepting error." << endl;
}
if(new_fd == INVALID_SOCKET){
cout<<"-INVALID SOCKET ERROR." << endl;
}
char buffer[128];
while(true){
int ret_val;
ret_val = recv(new_fd,buffer,sizeof(buffer),0);
if(ret_val == -1){
cout<<"Receiving Error." << endl;
break;
}else if(ret_val == 0){
cout<<"Connection has been closed!." << endl;
break;
}else{
cout<<"Server: " << buffer<< endl;
}
}
cout<<"-Closing connection" << endl;
closesocket(new_fd);
}else{
cout<<"-WSAStartup Initialization failed." << endl;
if(WSACleanup()!=0){
cout<<"-WSACleanup Successful." << endl;
}else{
cout<<"-WSACleanup Failed." << endl;
}
}
return 0;
}
client
/*client*/
#define _WIN32_WINNT 0x501
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std;
#define PORT "3490"
#define SERVER "localhost"
const int winsockVersion = 2;
int main(void){
WSADATA wsadata;
if ( (WSAStartup(MAKEWORD(2,0),&wsadata)) == 0){
cout<<"-WSAStartup Initialized." << endl;
struct addrinfo hints, *res;
int sockfd;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(SERVER,PORT,&hints,&res) != 0){
cout<<"-getaddrinfo unsuccessful." << endl;
}
if ( (sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol)) == -1 ){
cout<<"-Unable to create socket." << endl;
}
if ( (connect(sockfd,res->ai_addr,res->ai_addrlen)) != -1 ){
cout<<"-Connection Established." << endl;
}
cout<<"-Client connecting to: " << res->ai_addr << endl;
while(true){
string text_buff;
cout<<"Enter text: ";
getline(cin,text_buff);
if( (send(sockfd,text_buff.c_str(),text_buff.length()+1,0)) != -1 ){
cout<<"-text_buff sent!." << endl;
}
}
}else{
cout<<"-WSAStartup Initialization failed." << endl;
if(WSACleanup()!=0){
cout<<"-WSACleanup Successful." << endl;
}else{
cout<<"-WSACleanup Failed." << endl;
}
}
return 0;
}
I know how (i think) to specify the client in order to make it connect to my IP address XXX.XX.XXX.XX by changing the SERVER in client.cpp, But I'm not sure how to get the server to listen on this?.
Take a look here:
C++ strange socket data
This line:
addrinfo.sin_addr.s_addr = INADDR_ANY;
specifies any address. See here:
http://en.wikipedia.org/wiki/Getaddrinfo
for getaddrinfo if you want to use a specific IP or a hostname instead of any.
getaddrinfo takes as first option the identity of the server - that could be a name you can lookup in the dns or an ip address.
when you specify null on your 'server' side it implies localhost, on the client you specifically set local host.
The MSDN doc
The function your using is going to report back a list of possible addrinfo, you happen to be binding the first one.
At the moment you are hinting you want a stream. the rest is up to the resolver, so you will get stuff on all ips for localhost (loopback, wireless, ether, wan), and any port, on ipv4 and ipv6.
You need to be more specific about your hints, or perhaps skip this function and specify the port and address directly.
Ive written and compiled a server program that is meant to echo onto the the screen whatever the client application types in, the code is as below.
/*Server */
#define _WIN32_WINNT 0x501
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std;
const int winsock_version = 2;
#define PORT "3490"
#define MAX_NUM_CONNECTIONS 10
int main(void){
WSADATA wsadata;
if (WSAStartup(MAKEWORD(winsock_version,0),&wsadata) == 0){
cout<<"-WSAStartup Initialized." << endl;
struct addrinfo hints,*res;
int sock_fd;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if (getaddrinfo(NULL,PORT,&hints,&res) != 0){
cout<<"-Call to getaddress was unsucceful." << endl;
}
if( (sock_fd = socket(res->ai_family,res->ai_socktype,res->ai_protocol)) == -1){
cout<<"-Unable to Create socket." << endl;
}
if ( (bind(sock_fd, res->ai_addr, res->ai_addrlen)) != -1 ){
cout<<"-binding successful." << endl;
}
if ( (listen(sock_fd,MAX_NUM_CONNECTIONS)) != -1){
cout<<"-Listening for incoming connections." << endl;
}
//-------------------------------------------------------------
struct sockaddr_storage incming_info;
socklen_t sin_size;
sin_size = sizeof incming_info;
int new_fd;
new_fd = accept(sock_fd, (struct sockaddr*)&incming_info,&sin_size);
if (new_fd == -1){
cout<<"-Accepting error." << endl;
}
if(new_fd == INVALID_SOCKET){
cout<<"-INVALID SOCKET ERROR." << endl;
}
closesocket(new_fd);
//-------------------------------------------------------------
cout<<"Connected?" << endl;
while(true){
int ret_val;
char buffer[128];
ret_val = recv(new_fd,buffer,sizeof(buffer),0);
if(ret_val == -1){
cout<<"Receiving Error." << endl;
break;
}else if(ret_val == 0){
cout<<"Connection has been closed!." << endl;
break;
}else{
cout<<"---Server Echoeing what was recieved from client---" << endl;
cout<<"Server: " << buffer << endl;
}
closesocket(new_fd);
}
cout<<"-Closing connection" << endl;
}else{
cout<<"-WSAStartup Initialization failed." << endl;
if(WSACleanup()!=0){
cout<<"-WSACleanup Successful." << endl;
}else{
cout<<"-WSACleanup Failed." << endl;
}
}
return 0;
}
The whole thing compiles and runs, however when I try to use putty and connect to localhost on port 3490 the server dies and prints out "Receiving Error". what is causing this problem?
Immediately after you accept the new socket into new_fd, you call closesocket on it (below). You should not do that until you are done receiving. If you want to close the listener socket at this point, you should be calling closesocket(sock_fd) instead.
int new_fd;
new_fd = accept(sock_fd, (struct sockaddr*)&incming_info,&sin_size);
if (new_fd == -1){
cout<<"-Accepting error." << endl;
}
if(new_fd == INVALID_SOCKET){
cout<<"-INVALID SOCKET ERROR." << endl;
}
closesocket(new_fd);