Hello, I'm learning winsock programming, and now I've made simple client to server messenger.
The problem I have is that I get extra characters on the server when I send string of characters from the client...
That happens if the string has 1, 2, 3, 5, 12, 13, 14 etc... characters.
Here are screenshots of the client and the server ( I used number 1 as data to send ): ....
And the source codes of the client and the server...
Client:
Server:Code:#include <iostream> #include <string> #include <winsock.h> using namespace std; int main() { label1: WSADATA WSAData; WSAStartup(MAKEWORD(2,0), &WSAData); SOCKET theClient; SOCKADDR_IN sin; char buffer[1024]; string isprati; getline(cin, isprati); size_t golemina = isprati.size(); char baranje[golemina]; strncpy( baranje, isprati.c_str(), golemina ); theClient = socket(AF_INET, SOCK_STREAM, 0); sin.sin_addr.s_addr = inet_addr("127.0.0.1"); // localhost sin.sin_family = AF_INET; sin.sin_port = htons(8888); // Port connect(theClient, (SOCKADDR *)&sin, sizeof(sin)); // Connecting to the server send(theClient, baranje, strlen(baranje), 0); // Sending the string closesocket(theClient); // Closing the socket WSACleanup(); goto label1; system("PAUSE"); return 0; }
Why the sent data from the client is not equal to the data received in the server ( those extra charracters appear ) ?Code:#include <iostream> #include <string> #include <winsock.h> using namespace std; int main() { label1: WSADATA WSAData; // We begin by initializing Winsock WSAStartup(MAKEWORD(2,0), &WSAData); // Next, create the listening socket SOCKET listeningSocket; listeningSocket = socket(AF_INET, // Go over TCP/IP SOCK_STREAM, // This is a stream-oriented socket IPPROTO_TCP); // Use TCP rather than UDP // Use a SOCKADDR_IN struct to fill in address information SOCKADDR_IN serverInfo; serverInfo.sin_family = AF_INET; serverInfo.sin_addr.s_addr = INADDR_ANY; // Since this socket is listening for connections, // any local address will do serverInfo.sin_port = htons(8888); // Convert integer 8888 to network-byte order // and insert into the port field // Bind the socket to our local server address bind(listeningSocket, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr)); // Make the socket listen listen(listeningSocket, 1); // Up to 1 connections may wait at any // one time to be accept()'ed // Wait for a client SOCKET theClient; theClient = accept(listeningSocket, NULL, // Optionally, address of a SOCKADDR_IN struct NULL); // Optionally, address of variable containing // sizeof ( struct SOCKADDR_IN ) char buffer[100] = ""; recv(theClient, buffer, sizeof(buffer),0); //system(buffer); cout << buffer << endl; closesocket(theClient); closesocket(listeningSocket); // Shutdown Winsock WSACleanup(); goto label1; system("PAUSE"); return 0; }
Where do I make mistake?
Thanks In Advance...



LinkBack URL
About LinkBacks


