473,320 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Send/recv struct over TCP

1
I have to type two strings in a client and send them with a struct to server. Then the server does 'c = a + b' and sends a news struct with { a, b, c } to client. If 'a' or 'b' received is quit, server sends to client bye.

Client receives the struct and prints 'c'. If it is 'bye' it closes connection, else it returns to asking the input of 'a' and 'b' and the cycle begins again.

Client:

Expand|Select|Wrap|Line Numbers
  1. #if defined WIN32
  2.     #include <Winsock2.h>
  3.     #else
  4.     #define closesocket close
  5.     #include <sys/socket.h>
  6.     #include <arpa/inet.h>
  7.     #include <unistd.h>
  8.     #endif
  9.     #include <stdio.h>
  10.     #include <stdlib.h>
  11.     #include <string.h>
  12.  
  13.     #define BUFSIZE 30
  14.  
  15.     void ClearWinSock() {
  16.     #if defined WIN32
  17.         WSACleanup();
  18.     #endif
  19.     }
  20.  
  21.     //-----------------------------INIZIALIZZAZIONE WSADATA
  22.  
  23.     int main (void) {
  24.     #if defined WIN32
  25.  
  26.         WSADATA wsaData;
  27.         int iResult = WSAStartup (MAKEWORD (2,2), &wsaData);
  28.  
  29.         if (iResult !=0) {
  30.             printf ("error at WSASturtup\n");
  31.             return 0;
  32.             }
  33.  
  34.     #endif
  35.  
  36.     //--------------------------------CREAZIONE SOCKET
  37.  
  38.         int Csocket;
  39.  
  40.         Csocket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
  41.  
  42.         if (Csocket < 0) {
  43.  
  44.         printf ("socket creation failed");
  45.         closesocket (Csocket);
  46.         ClearWinSock();
  47.         return 0;
  48.         }
  49.  
  50.         char s_address[BUFSIZE];
  51.                 printf ("Inserisci l'indirizzo dell'host a cui connetterti\n");
  52.                 scanf ("%s", s_address);
  53.  
  54.                 int port;
  55.                 printf ("Inserisci la porta a cui connetterti\n");
  56.                 scanf("%d", &port);
  57.  
  58.                 struct sockaddr_in sad;
  59.                     memset (&sad, 0, sizeof(sad));
  60.                     sad.sin_family = AF_INET;
  61.                     sad.sin_addr.s_addr = inet_addr(s_address);
  62.                     sad.sin_port = htons (port);
  63.  
  64.     //------------------------------CONNESSIONE AL SERVER
  65.  
  66.        if (connect(Csocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
  67.             printf ("failed to connect\n");
  68.             closesocket (Csocket);
  69.             ClearWinSock();
  70.             return 0;
  71.        }
  72.  
  73.     //-----------------------------RICEZIONE STRINGA DAL SERVER
  74.  
  75.        char buf[BUFSIZE];
  76.  
  77.        int read = recv (Csocket, buf, BUFSIZE - 1, 0);
  78.  
  79.        if (read <=0) {
  80.  
  81.         printf ("Qualcosa non và!\n");
  82.        }
  83.  
  84.        else {
  85.         buf[read] = '\0';  //tappo stringa per sicurezza
  86.         printf("Server scrive: %s\n", buf);
  87.        }
  88.  
  89.  
  90.     //------------------------------STRUTTURA DI STRINGHE
  91.  
  92.          struct stringab {
  93.                                 char a[30];
  94.                                 char b[30];
  95.                                 char c[70];
  96.                             } ab;
  97.  
  98.  
  99.                             void* abptr = &ab;
  100.  
  101.  
  102.                 printf ("Inserisci prima stringa\n");
  103.                 scanf ("%s", ab.a);
  104.  
  105.  
  106.                             printf ("Inserisci seconda stringa\n");
  107.                             scanf ("%s", ab.b);
  108.  
  109.  
  110.  
  111.         if (send(Csocket, (char*)abptr, sizeof(ab), 0) != sizeof(ab)) {
  112.                printf("client-send() sent a different number of bytes than expected");
  113.                closesocket(Csocket);
  114.                ClearWinSock();
  115.                system ("pause");
  116.                return 0;
  117.            }
  118.  
  119.  printf ("\n");
  120.    closesocket (Csocket);
  121.    system ("pause");
  122.    ClearWinSock();
  123.    return 0;
  124.  
  125.    }
Server:

Expand|Select|Wrap|Line Numbers
  1. #if defined WIN32
  2. #include <Winsock2.h>
  3. #else
  4. #define closesocket close
  5. #include <sys/socket.h>
  6. #include <arpa/inet.h>
  7. #include <unistd.h>
  8. #endif
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12.  
  13. #define BUFSIZE 30
  14.  
  15. void ClearWinSock() {
  16. #if defined WIN32
  17.     WSACleanup();
  18. #endif
  19. }
  20.  
  21. int main(void) {
  22.  
  23. //---------------------------INIZIALIZZAZIONE WSADATA
  24.  
  25. #if defined WIN32
  26.  
  27.     WSADATA wsaData;
  28.     int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
  29.     if (iResult != 0) {
  30.         printf ("Error at WSAStartup");
  31.         return 0;
  32.     }
  33.  
  34. #endif
  35.  
  36. //-------------------------------CREAZIONE SOCKET
  37.  
  38.     int Mysocket;
  39.     Mysocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  40.  
  41.     //Valutare la presenza di errori per assicurarsi che la socket sia valida.
  42.     if (Mysocket < 0) {
  43.         printf("socket creation failed\n");
  44.         return 0;
  45.     }
  46.  
  47.     //Assegnazione indirizzo alla socket.
  48.     struct sockaddr_in sad;
  49.     memset(&sad, 0, sizeof(sad));
  50.     sad.sin_family = AF_INET;
  51.     sad.sin_addr.s_addr = inet_addr ("127.0.0.1");
  52.     sad.sin_port = htons (9888);
  53.  
  54. //------------------------ASSEGNAZIONE PORTA E IP ALLA SOCKET
  55.  
  56. if (bind(Mysocket, (struct sockaddr*) &sad, sizeof(sad)) < 0) {
  57.     printf ("bind() failed\n");
  58.     closesocket(Mysocket);
  59.     return 0;
  60. }
  61.  
  62. //---------------------------SETTAGGIO SOCKET ALL'ASCOLTO
  63.  
  64. int qlen = 10; //numero client che il server può gestire
  65.  
  66. if (listen (Mysocket, qlen) < 0) {
  67.  
  68.     printf("listen() failed\n");
  69.     closesocket(Mysocket);
  70.     return 0;
  71. }
  72.  
  73. struct sockaddr_in cad;  // struttura per l'indirizzo del cient
  74. int Csocket;             // descrittore socket per il client
  75. int clientlen;           // lunghezza indirizzo del client
  76.  
  77. //------------------------------ACCETTA LA CONNESSIONE
  78.  
  79. while (1) {
  80.  
  81.     printf("In attesa di un client con cui comunicare...\n");
  82.     memset(&cad, 0, sizeof(cad));
  83.     clientlen = sizeof(cad);       // assegna la dimensione dell'indirizzo del client
  84.  
  85.     if((Csocket = accept(Mysocket, (struct sockaddr*) &cad, &clientlen)) < 0) {
  86.         printf ("accept failed\n");
  87.         closesocket(Mysocket);
  88.         ClearWinSock();
  89.         return 0;
  90.     }
  91.  
  92.  
  93.     printf("Connessione stabilita con il client il cui indirizzo e' %s \n\n", inet_ntoa(cad.sin_addr));
  94.  
  95. //---------------------------------------INVIO STRINGA AL CLIENT
  96.  
  97.     char* inputString = "Connessione avvenuta!";
  98.     int stringlen = strlen(inputString);
  99.  
  100.  
  101.     if (send(Csocket, inputString, stringlen, 0) != stringlen) {
  102.         printf("client-send() sent a different number of bytes than expected");
  103.         closesocket(Csocket);
  104.         ClearWinSock();
  105.         system ("pause");
  106.         return 0;
  107.     }
  108.  
  109. printf ("\n");
  110. closesocket (Csocket);
  111. system ("pause");
  112. ClearWinSock();
  113. return 0;
  114.  
  115. }
So, did I send the struct to server in this manner? How the server could recv() this struct and do c = a + b re-building and re-sending the struct?
Oct 24 '17 #1
0 2210

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: ANaiveProgrammer | last post by:
Hi all I have made the following two structs and size is not according to what is supposed to be, so please ponder over following and identify if im wrong... please also mention what would be...
6
by: Tom | last post by:
I try to write a simple tcp based job queue server. It's purpose is to get commands from a client and store them in a queue (STL). The server has a thread which checks periodically the queue,...
4
by: Abubakar | last post by:
Hi, I am writing a server in C# and client in C++ (pure, not managed). The communication goes on through sockets. In C# I am using NetworkStream to send text data (by converting it to byte array)...
5
by: nicolas ETIENNE | last post by:
Hello, I want to send through Socket a struct So, i'd like to do, as I did before in C++, something like send((void*)myStruct); where myStruct is a struct with basic types
0
by: Rob | last post by:
Any opinions on the best way to send a small text struct from a legacy win32 (non-MFC) app to a C# app? There seem to be a lot of options, but I'm trying to keep the Win32 side as simple as...
6
by: Jack | last post by:
Hi, All, is it possible to send a struct using the the send function. Here is what I mean typedef struct{ int ID; char name; }sampleStruct; int main(){
4
by: =?Utf-8?B?RWl0YW4=?= | last post by:
Hello, I need to send a "struct" to an embeded CPU over the Ethernet. The struct is defined like this: public struct MyStruct { public double dVar1;
3
by: Tolga Ongunsu | last post by:
I want to send the struct to another Program by using TcpClient. I found a method that converts struct to byte but it doesnot working correctly. What am i missing? public struct student { ...
0
by: Xionbox | last post by:
Hello everybody, The error I have seems very easy to solve, but for some odd reason I can't seem to solve it. Anyways, here's my "setup". I created a server running on localhost:1200 (telnet...
4
by: shravansofts | last post by:
hi Mates, First of all thanks for this wonderful Programmers Community. Recently i started to learn Socket Programming. i have some doubts, hope u ppl will clarif them. i am trying to code a...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.