Home » Language IDEs » C / C++ IDE (CDT) » sending/receiving/manipulating strings with sockets
sending/receiving/manipulating strings with sockets [message #1718654] |
Mon, 28 December 2015 18:48 |
Marco R. Messages: 6 Registered: December 2015 |
Junior Member |
|
|
I have a little problem with sending and receiving a string with socket between a server and a client. In this code, first the server sends "connection established ("connessione avvenuta" in Italian) to the client (which prints it on screen), then the client scans a string and sends it to the server, which deletes the vowels and sends it again to the client. When I print it with client, strange chars appears at the end of the string, I think because I didn't close it well. How to do this?
I tryed using strlen+1 in some points but there is still the same error.
**SERVER SIDE**
#if defined WIN32
#include <winsock2.h>
#else
#define closesocket close
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 30
void ClearWinSock() {
#if defined WIN32
WSACleanup();
#endif
}
int main(void) {
//---------------------------INIZIALIZZAZIONE WSADATA
#if defined WIN32
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf ("Error at WSAStartup");
return 0;
}
#endif
//-------------------------------CREAZIONE SOCKET
int Mysocket;
Mysocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Mysocket < 0) {
printf("socket creation failed\n");
return 0;
}
struct sockaddr_in sad;
memset(&sad, 0, sizeof(sad));
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = inet_addr ("127.0.0.1");
sad.sin_port = htons (9888);
//------------------------ASSEGNAZIONE PORTA E IP ALLA SOCKET
if (bind(Mysocket, (struct sockaddr*) &sad, sizeof(sad)) <0) {
printf ("bind() failed\n");
closesocket(Mysocket);
return 0;
}
//---------------------------SETTAGGIO SOCKET ALL'ASCOLTO
int qlen = 10;
if (listen (Mysocket, qlen) < 0) {
printf("listen() failed\n");
closesocket(Mysocket);
return 0;
}
struct sockaddr_in cad;
int Csocket;
int clientlen;
//------------------------------ACCETTA LA CONNESSIONE
while (1) {
printf("In attesa di un client con cui comunicare\n");
memset(&cad, 0, sizeof(cad));
clientlen = sizeof(cad);
if((Csocket = accept(Mysocket, (struct sockaddr*) &cad, &clientlen)) < 0) {
printf ("accept failed\n");
closesocket(Mysocket);
ClearWinSock();
return 0;
}
printf("connesso con il client\n");
//---------------------------------------INVIO STRINGA AL CLIENT
char* inputString = "connessione avvenuta";
int stringlen = strlen(inputString);
if (send(Csocket, inputString, stringlen, 0) != stringlen) {
printf("client-send() sent a different number of bytes than expected");
closesocket(Csocket);
ClearWinSock();
system ("pause");
return 0;
}
//-------------------------------------RICEZIONE STRINGA DAL CLIENT
char str1[BUFSIZE+1]; char str1des[BUFSIZE+1];
int i,j=0;
//recv (Csocket, str1, BUFSIZE - 1, 0);
int read = recv(Csocket, str1, BUFSIZE-1, 0); str1[read] = '\0';
//-------------------------------ELIMINAZIONE VOCALI DALLA STRINGA RICEVUTA
for(i=0;i<=strlen(str1)+1;i++) {
if(str1[i]=='a'||str1[i]=='e'||str1[i]=='i'||str1[i]=='o'||str1[i]=='u' ||str1[i]=='A'||str1[i]=='E'||str1[i]=='I'||str1[i]=='O'||str1[i]=='U')
str1[i]=' ';
else
str1des[j++]=str1[i];
}
str1des[j]='\0';
//-----------------------------------INVIO STRINGA ELABORATA AL CLIENT
if (send(Csocket, str1des, strlen(str1des), 0) != strlen(str1des)) {
printf("client-send() sent a different number of bytes than expected");
closesocket(Csocket);
ClearWinSock();
system ("pause");
return 0;
}
}
//------------------------------------------CHIUSURA CONNESSIONE
closesocket (Csocket);
ClearWinSock();
printf ("\n");
system ("pause");
return 0;
}
**CLIENT SIDE**
#if defined WIN32
#include <winsock2.h>
#else
#define closesocket close
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 30
void ClearWinSock() {
#if defined WIN32
WSACleanup();
#endif
}
//-----------------------------INIZIALIZZAZIONE WSADATA
int main (void) {
#if defined WIN32
WSADATA wsaData;
int iResult = WSAStartup (MAKEWORD (2,2), &wsaData);
if (iResult !=0) {
printf ("error at WSASturtup\n");
return 0;
}
#endif
//--------------------------------CREAZIONE SOCKET
int Csocket;
Csocket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Csocket < 0) {
printf ("socket creation failed");
closesocket (Csocket);
ClearWinSock();
return 0;
}
//--------------------------COSTRUZIONE INDIRIZZO SERVER
struct sockaddr_in sad;
memset (&sad, 0, sizeof(sad));
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = inet_addr ("127.0.0.1");
sad.sin_port = htons (9888);
//------------------------------CONNESSIONE AL SERVER
if (connect(Csocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
printf ("failed to connect\n");
closesocket (Csocket);
ClearWinSock();
return 0;
}
//-----------------------------RICEZIONE DATI DAL SERVER
char buf[BUFSIZE+1];
int read = recv (Csocket, buf, BUFSIZE - 1, 0);
if (read <=0) {
printf ("Qualcosa non và!\n");
}
else {
buf[read+1] = '\0';
printf("Server scrive: %s\n", buf);
}
//----------------------------INVIO PRIMA STRINGA AL SERVER
char str1[BUFSIZE+1]; int stringlen = strlen(str1);
printf ("inserisci prima stringa:\n");
scanf ("%s", str1);
if (send(Csocket, str1, stringlen, 0) != stringlen) {
printf("client-send() sent a different number of bytes than expected");
closesocket(Csocket);
ClearWinSock();
system ("pause");
return 0;
}
//------------------------------RICEZIONE STRINGA ELABORATA DAL SERVER
char buf2[BUFSIZE+1];
int read2 = recv (Csocket, buf2, BUFSIZE - 1, 0);
if (read2 <=0) {
printf ("Qualcosa non và!\n");
}
else {
buf2[read+1] = 0;
printf("Server scrive: %s\n", buf2);
}
//---------------------------------------CHIUSURA CONNESSIONE
closesocket (Csocket);
ClearWinSock();
printf ("\n");
system ("pause");
return 0;
}
|
|
|
Re: sending/receiving/manipulating strings with sockets [message #1718663 is a reply to message #1718654] |
Mon, 28 December 2015 20:40 |
David Vavra Messages: 1426 Registered: October 2012 |
Senior Member |
|
|
In the extracted code below, you are setting the stringlen to effectively a random number. Variable str1 has not been initialized.
char str1[BUFSIZE+1]; int stringlen = strlen(str1); // <---- str1 unitialized so stringlen == ??
printf ("inserisci prima stringa:\n");
scanf ("%s", str1);
if (send(Csocket, str1, stringlen, 0) != stringlen) { // <--- sends ?? number of chars
Perhaps better code:
char str1[BUFSIZE+1]; int stringlen;
printf ("inserisci prima stringa:\n");
scanf ("%s", str1);
stringlen = strlen(str1);
if (send(Csocket, str1, stringlen, 0) != stringlen) {
Not that it matter but the loop removing the vowels pointlessly changes str1 to a space when a vowel is encountered. You don't seem to use str1 again. You are also transmitting N messages in the same loop but I'm guessing that was intentional.
|
|
| |
Re: sending/receiving/manipulating strings with sockets [message #1718740 is a reply to message #1718692] |
Tue, 29 December 2015 16:17 |
David Vavra Messages: 1426 Registered: October 2012 |
Senior Member |
|
|
I meant there is no reason for your code to change the vowel in str1 to a space since you don't use str1 later. I didn't say anything about pointers.
You could have found these problems by stepping through the code with a debugger or by simplifying the code to avoid using sockets until it's working. For example, you could make the server and client into two subroutines passing the message as a parameter. After they are both working THEN use sockets. Such as below:
// A debugging test
int Server(const char * inp, char out[]) {
// insert code to do server actions to produce out for sending
return strlen(out);
}
void Client(char inp[]) {
// code to do client actions on received message
}
int main() {
const char * initialMsg = "what ever";
char message[100];
int messageLen = Server(initialMsg, message);
message[messageLen+1] = 0;
Client(message);
}
Or something similar. I leave the details to you.
This subject is beyond the scope of this forum which is to address problems related CDT and not to debug unrelated code . Fixing your code is really your job; no ours.
[Updated on: Tue, 29 December 2015 16:28] Report message to a moderator
|
|
| |
Re: sending/receiving/manipulating strings with sockets [message #1718760 is a reply to message #1718748] |
Tue, 29 December 2015 20:40 |
David Vavra Messages: 1426 Registered: October 2012 |
Senior Member |
|
|
stackoverflow.com used to be the place for things like these but anymore most questions are left untouched unless someone thinks they are interesting.
You could try it though.
But before you do that, try tracking down what's happening using a debugger or other means. If you think about it, you are asking someone to download your code and do it for you. You've posted your entire program; later fixed some obvious problems; and expected others to tell you what you did wrong. Intended or not, you are coming across as someone seeking an answer instead of help in finding one. IOW: laziness.
But we all have blind spots and there is an initial tendency to flounder but you really shouldn't wallow in it. First step you should do is isolate the code from external influences such as the socket interface such as I outlined above. If it is working fine there then and only then should you think it has anything to do with the interface and, even then, the first thought should be what is wrong with the calls. Once you've narrowed down the issue then try to succinctly ask what can be done to resolve or avoid it. Try to reproduce the problem with the least amount of code so someone doesn't have to plow through a lot.
The basic steps in troubleshooting are:
First prove that small pieces work by isolation when possible.
Then look for interactions between the pieces.
Then consider misuse of system/API calls.
If all else fails, reproduce the problem with the smallest amount of code to present the problem to others.
What you've done reminds me of the time years ago when I was a User Consultant at my university. A physics grad student walked in with what must have been a complete box of printout; opened it to a middle page containing nothing but numbers; and asked "Why is this one a zero?" My first reaction was to think, "How should I know?" Surprisingly, all I had to do was listen to him explain the program step-by-step and he answered his own question.
When you're faced with failing code, systematically isolate the problem.
|
|
|
Goto Forum:
Current Time: Fri Mar 29 01:09:02 GMT 2024
Powered by FUDForum. Page generated in 0.03364 seconds
|