I have a problem related with client/server communication via socket when I do consecutive send and after that a recv on client. Example:
Case A:
Client Server
send(...);----------->While(recv(...)>0){
send(...);-----------> print(message);
send(...);----------->}
recv(...);----------->Send(...);
The server receives the 3 messages and send the last answer, but the recv on client failed with SOCKET_ERROR with WSAGetLastError() value of 10060.
The only way to make this case to work is when I add a shutdown(...,SD_SEND) after the last send on client.
Why the case A have this behaviour? and why it works only when I add the shutdown() command?
But if I do:
Case B:
Client Server
send(...);----------->While(recv(...)>0){
recv(...);-----------> send(...);
send(...);-----------> ...
recv(...);-----------> ...
send(...);-----------> ...
recv(...);----------->}
It works fine, server/client receives and send each message.
Here is the code for case A:
Client:
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 1024
#define DEFAULT_PORT "27015"
int main() {
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
ADDRINFOA *ptr = NULL, *result = NULL, hints;
char *ans, *sendbuf = "message\0";
char recvbuf[1024];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
ans=new char[1024];
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
printf("--> Initializing Winsock...\n*** Version: %s\n", wsaData.szDescription);
if (iResult != 0) {
printf("*** Could not initialize Socket.\n*** Error code: %d", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
printf("--> Setting server address...\n");
printf("--> local ip: 127.0.0.1 at port: %s...\n",DEFAULT_PORT);
if ( iResult != 0 ) {
printf("*** Error in setting server address.\n*** Error code: %d", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
printf("--> Creating client socket object...\n");
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("*** Error creating socket.\n*** Error code: %d\n",WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
if(setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)new int(1000), sizeof(int))){
WSACleanup();
//strcpy(recvbuf, "EX_95");
return -5; // Error setting recv timeout.
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
printf("*** Client ready *** \n\n");
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("*** Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("*** Send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("<-- Bytes Sent: %ld\n", iResult);
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("*** Send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("<-- Bytes Sent: %ld\n", iResult);
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("*** Send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("<-- Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
/*iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}*/
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
// cleanup
closesocket(ConnectSocket);
WSACleanup();
system("pause");
return 0;
}
Server:
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#include <iostream>
#include <Winsock2.h>
#include <Ws2tcpip.h>
#include <string>
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
const char* DEFAULT_PORT = "27015";
const int DEFAULT_BUFLEN = 1024;
using namespace std;
int main(){
//Connection Variables.
WSADATA wsaData;
ADDRINFOA *result = NULL, hints;
SOCKADDR *clientInfo = NULL;
int iResult;
//Receive Variables.
char recvBuff[DEFAULT_BUFLEN];
int recvBuffLen = DEFAULT_BUFLEN;
int iSendResult;
//Server/Client sockets.
SOCKET ListenSocket = INVALID_SOCKET; //SOCKET for the server to listen for client connections.
SOCKET ClientSocket = INVALID_SOCKET;
//Initialize Winsock
iResult = WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
printf("--> Initializing Winsock...\n*** Version: %s\n", wsaData.szDescription);
if ( iResult != 0 ){
printf("*** Could not initialize Socket.\n*** Error code: %d", iResult);
return 1;
}
//Initialize hints allocated memory.
ZeroMemory( &hints, sizeof( hints ) );
hints.ai_family = AF_INET; //AF_INET is used to specify the IPv4 address family.
hints.ai_socktype = SOCK_STREAM; //SOCK_STREAM is used to specify a stream socket.
hints.ai_protocol = IPPROTO_TCP; //IPPROTO_TCP is used to specify the TCP protocol.
hints.ai_flags = AI_PASSIVE; //AI_PASSIVE The socket address will be used in a call to the bind function.
printf("--> Getting address info from server...\n");
iResult = getaddrinfo( NULL, DEFAULT_PORT, &hints, &result );
if( iResult != 0 ){
printf("*** Error in getting address info from server.\n*** Error code: %d", iResult);
WSACleanup();
return 2;
}
printf("--> Creating server socket object...\n");
//printf("Create socket to ip: %s at port: %s\n", inet_ntoa(((SOCKADDR_IN*)(result->ai_addr))->sin_addr),DEFAULT_PORT);
ListenSocket = socket( result->ai_family, result->ai_socktype, result->ai_protocol );
if( ListenSocket == INVALID_SOCKET ){
printf("*** Error creating socket.\n*** Error code: %d\n",WSAGetLastError());
freeaddrinfo( result );
WSACleanup();
return 3;
}
//BIND()->Associates a local address to a socket.
printf("--> Bind listen object to local ip: 127.0.0.1 at port: %s...\n",DEFAULT_PORT);
iResult = bind( ListenSocket, result->ai_addr, result->ai_addrlen );
if( iResult == SOCKET_ERROR ){
printf("*** Binding failed.\n*** Error code: %d\n", WSAGetLastError());
closesocket( ListenSocket );
freeaddrinfo( result );
WSACleanup();
return 4;
}
freeaddrinfo(result);
printf("*** Server ONLINE: Listening...\n\n");
iResult = listen( ListenSocket, SOMAXCONN );
if( iResult == SOCKET_ERROR ){
printf("*** Failed start listening.\n*** Error code: %d\n",WSAGetLastError());
closesocket( ListenSocket );
freeaddrinfo( result );
WSACleanup();
return 5;
}
for(;1;){
ClientSocket = accept( ListenSocket,clientInfo, NULL );
if( ClientSocket == INVALID_SOCKET ){
printf("*** Failed accepting connection from client.\n*** Error code: %d\n",WSAGetLastError());
continue;
}
else{
printf("--> Connection accepted from client.\n");
iResult=1;
while(iResult > 0){
iResult = recv( ClientSocket, recvBuff, recvBuffLen, 0 );
if( iResult > 0 ){
printf("--> Message received: %s\n--> Total: %d\n", recvBuff, iResult);
}
}
iSendResult = send( ClientSocket, "Answer\0", DEFAULT_BUFLEN, 0 );
if( iSendResult == SOCKET_ERROR ){
printf("*** Sending data failed.\n*** Error code: %d\n",WSAGetLastError());
continue;
}
else{
printf("--> Sent: %d bytes\n", iSendResult);
}
printf("*** Closing connection... \n\n");
iResult = shutdown( ClientSocket, SD_BOTH );
if( iResult == SOCKET_ERROR ){
printf("*** Shutdown client failed.\nError code: %d\n",WSAGetLastError());
closesocket( ClientSocket );
WSACleanup();
return 9;
}
}
}
closesocket( ClientSocket );
WSACleanup();
system("pause");
return 0;
}
Thanks in advance!!!!
Nicolas Miranda S.
The server is blocked inside the recv call when the client waits for the response and thus cannot send anything. Your receiver timeout is 1 second, so after 1 second the client generates a timeout error (WSAETIMEDOUT == 10060).
When you do the shutdown, you only specify SD_SEND, so the connection is not closed, but it causes the server to exit recv, and it is therefore able to send the response.
Note: recv will block until something is received for a stream socket (SOCK_STREAM). You should look at the select() function to see how you can "peek" whether there is data available before calling recv.
Here is an example of using select:
fd_set fds;
timeval tv;
tv.tv_sec = 5000;
fds.fd_count = 1;
fds.fd_array[0] = ClientSocket;
int select_result = select(1, &fds, NULL, NULL, &tv);
If select_result == 0, there was a timeout. Otherwise one of the sockets in fd_set is ready with data. Here there's just one and it was specified as a readfds in the select call.
You need to re-arrange the app so that you have some event (receive the third message, for example, or some timeout without anything received, or something in the message itself) that causes the server to send the response. You can use a second thread for responses but that's beyond what I can show in a short answer.
Related
I need to send some data to a device. For that, I'm trying to use a WinSock socket client. The connection in principal works, but I get no data back, only an ACK. I tried this same test with a Putty client, there I was receiving data. I was looking with Wireshark and I saw that my WinSock client is sending a FIN after transmitting the data. That is not the case with Putty. I know the FIN will be sent because of shutdown(SD_SEND), but how can I handle this in another way? You can see this in the Pictures below.
Wireshark for WinSock:
Wireshark for Putty:
Here is my client code:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "8000"
#define DEFAULT_IP "127.0.0.1"
//int __cdecl main(int argc, char** argv)
int __cdecl main()
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo* result = NULL,
* ptr = NULL,
hints;
const char* sendbuf = "M:UA 111111 SEP1,00000";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
// if (argc != 2) {
// printf("usage: %s server-name\n", argv[0]);
// return 1;
// }
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
// iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
iResult = getaddrinfo(DEFAULT_IP, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
else if (iResult == 0)
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while (iResult > 0);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
Putty is sending 2 extra bytes after each text. Presumably a CRLF line ending. Your Winsock code is not sending those 2 bytes. Chances are, the server is expecting a line break to arrive before sending data back to the client.
Try changing this:
const char* sendbuf = "M:UA 111111 SEP1,00000";
To this:
const char* sendbuf = "M:UA 111111 SEP1,00000\r\n";
And no, Putty is not sending a FIN, because it is a user-controlled terminal, and the user (you) hasn't indicated to it that further text will not be entered, so it just sits there waiting for more text to send.
Thanks for the fast respond. I tried this, but it will not work. Also I have looked into Wireshark for the Putty package, there were not two extra Bytes on the end.
INTRODUCTION:
I have studied the MSDN examples for blocking TCP server and blocking TCP client.
I wanted to try something simple, in view of modifying those examples to create simple chat application.
I have tried to implement the following, for a start:
send message from server
receive and display that message on client
send response from client
receive and display the response from client
RELEVANT INFORMATION
I apologize in advance for the lengthy code, but i strongly believe it is relevant for me to submit SSCCE for both client and the server, in order for community to stand a chance for solving the problem.
I have tried to keep the code as minimal as possible, but did not want to omit basic error checking.
You can copy/paste both in single .cpp file, and they should compile and run without problem:
Server code:
#undef UNICODE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main(void)
{
WSADATA wsaData;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int iResult;
char recvbuf[DEFAULT_BUFLEN] = "";
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// No longer need server socket,
// because I want to accept only 1 client
closesocket(ListenSocket);
// ===================== let us try to send a message...
std::string message = "Test message from server !!!";
int total = message.size();
const int messageLength = message.size();
while (iResult = send( ClientSocket,
// send only the missing part of the string, if send failed to deliver entire packet:
// we move the start of the string forward by messageLength - total
// while we send remaining number of bytes, which is held in total
message.substr(messageLength - total, total).c_str(), total, 0),
iResult > 0)
{
total -= iResult;
}
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
/* // adding this, seems to solve the problem ???
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
*/
// receive response from client...
while (iResult = recv(ClientSocket, recvbuf, recvbuflen, 0), iResult > 0)
{
printf("%s", recvbuf);
memset(recvbuf, '\0', sizeof(recvbuf));
}
if(iResult < 0)
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
getchar(); // so I can stop the console from immediately closing...
return 0;
}
Client code:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
#pragma comment (lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char recvbuf[DEFAULT_BUFLEN] = "";
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0)
{
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 )
{
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next)
{
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET)
{
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET)
{
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// receive message from server...
while (iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0), iResult > 0)
{
printf("%s", recvbuf);
memset(recvbuf, '\0', sizeof(recvbuf));
}
if(iResult < 0)
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// ===================== let us try to send a message...
std::string message = "Client response...";
int total = message.size();
const int messageLength = message.size();
while (iResult = send( ConnectSocket,
// send only the missing part of the string, if send failed to deliver entire packet:
// we move the start of the string forward by messageLength - total
// while we send remaining number of bytes, which is held in total
message.substr(messageLength - total, total).c_str(), total, 0),
iResult > 0)
{
total -= iResult;
}
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ConnectSocket);
WSACleanup();
getchar(); // so I can stop the console from immediately closing...
return 0;
}
PROBLEM:
I have implemented the solution, but did not get the expected result.
Server sends the message, client successfully receives and displays it, but then client gets stuck infinitely, instead of sending it's response to the server, which blocks the server infinitely as well.
MY EFFORTS TO SOLVE THIS:
First try:
Using the Debugger, I have placed breakpoint after client's receive block only to determine client never gets there after it receives first message.
I believe while loop should call recv again, which should return 0, thus forcing the loop to end.
Debugger doesn't even continue to show the content of client's receive buffer after I hit Continue, instead it exhibits behavior I can not describe at this moment since I am not a native English speaker.
Second try:
I have also tried to put receiving loop from server into thread, using CreateThread, but that did not help either.
I have also tried to put receiving loop from the client into thread, but that failed too.
I have tried to put both client and server receiving loops into thread, but that failed too.
Third try:
Finally, I have added the call to shutdown( ClientSocket, SD_SEND) in the server code, you shall find it at the lower part of the code, it is commented out.
This seems to fix the problem, but i am not sure if this is the right solution since i am just starting with Winsock.
QUESTIONS:
How can I bypass my "solution" of adding shutdown after send ?
If the above is the only way, should I do the same after recv and what argument should I send (SD_SEND, SD_RECEIVE or SD_BOTH) ?
Again, I apologize for lengthy post, but being new to this I have tried to provide as much info as possible in order to make your task easier.
After a brief glance at your code I would venture to guess that the following code block in the client:
while (iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0), iResult > 0)
{
printf("%s", recvbuf);
memset(recvbuf, '\0', sizeof(recvbuf));
}
is actually your issue. You mentioned that shutting down the socket on the serverside fixes the problem. With sockets, the recv call is going to block as long as the socket is alive or until data comes through, but when the socket is closed you will get a recv of 0.
Instead of looping on recv, if you want to just receive one message you should either loop back to the recv call after processing the first recv or you should poll on the socket to see if there is actually data available first.
I have question how can I change IP in this code I want connect with server which has IP : 109.95.202.122 I tried gethostname()and with this addr.sin_addr.s_addr = inet_addr("127.0.0.1"); but it works only with localhost please help me.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
For some reason, looks like the code you copied from someone. Let me try to see if I can help you.
If you changed the ip address in the right location, check if the ip address you want to connect have the port open and authorized for your access (From the look of the code, you can pass the ip address as a parameter to the application).
If you really tried to use the below code even when trying to access a different IP address, you need to know that localhost = 127.0.0.1, so it make sense that you can only connect to localhost.
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
I would recommend you to read a guide about socket programming to understand what each part of the code is doing. Take a look at this guide, it may help you.
I wanted to post this as a comment (and not answer), but look like since im a newbie at stackoverflow, I cant do that yet.
I am very new to c++. Recently I am trying to pass some data to a php file in c++ via the post method. I have tried a tutorial from MSDN send Function. The code is as follows:
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <conio.h>
// Link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT 27015
int main() {
//----------------------
// Declare and initialize variables.
int iResult;
WSADATA wsaData;
struct hostent *host;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
int recvbuflen = DEFAULT_BUFLEN;
char *sendbuf = "Client: sending data test";
char recvbuf[DEFAULT_BUFLEN] = "";
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup failed with error: %d\n", iResult);
return 1;
}
//----------------------
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientService.sin_port = htons( 80 );
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
if (iResult == SOCKET_ERROR) {
wprintf(L"connect failed with error: %d\n", WSAGetLastError() );
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
//----------------------
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %d\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
wprintf(L"shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
wprintf(L"Bytes received: %d\n", iResult);
else if ( iResult == 0 )
wprintf(L"Connection closed\n");
else
wprintf(L"recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
// close the socket
iResult = closesocket(ConnectSocket);
if (iResult == SOCKET_ERROR) {
wprintf(L"close failed with error: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
WSACleanup();
getch();
}
It sends data to the homepage of localhost but I would like to send data somewhere else in localhost(eg. like 'localhost/test/index.php'). If I change the code from clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" ); to clientService.sin_addr.s_addr = inet_addr( "127.0.0.1/test/index.php" ); then I receive some errors in the exe file. But the program compiles successfully.
Please give me a solution. What should I do now?
You are taking the wrong approach. The low-level socket layer only allows you to connect to a specific server (for example your local http server running on 127.0.0.1 listening on port 80) and send raw data. You need to talk HTTP with that server to really do what you want to do.
I suggest that if you are new to C++, you look at one of the many third-party libraries for C++ which allow you to "talk HTTP" with a http server - for example, libCurl
I am very new to networking,i am trying to open a socket and get a file from a server.
I am getting connection timeout error 100060.
my code is:-
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
if (argc != 1) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("74.125.236.83", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
printf("inside loop\n");
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
printf("%d\n",ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("socket error\n");
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", iResult);
// shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
Have you tried using AF_INET instead of AF_UNSPEC?
Maybe you should printf() the values in results, especially ptr->ai_addr, to make sure the resolution went fine.
And obviously check that a server is listen()ing and accept()ing on the other side; did you prove it, with, for instance:
telnet 74.125.236.83:27015
In this line:
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
you are initializing ptr to result. But result is never being set to a value != NULL, so the loop exits immediately.
From your code, it seems to me that you meant:
// Attempt to connect to an address until one succeeds
for(ptr=hints; ptr != NULL ;ptr=ptr->ai_next) {