Java Server and C++ Client

Hi everyone.

I have some experience on Matlab, Java and C++, but fot the type of programming I'm trying to do here, I'm basically a beginner.

Eventually, the main idea of this Server/Client is that the client will ask the server for time, receive the time, read the string
and sync its time to the server, assuming there is a time drift.

As of right now I have the server in Java and a client in Java that work. They are not syncing yet, but the client makes a request to
the server, which sends a string with the date and time and the client prints that string. We don't need the time sync part quite yet.
More importantly is to create a client on C++ that does the same that the one on Java does (I'll post both codes soon) and works with the Java server.

On the C++ side, I got a simple client/Server program and I'm trying to change the client enough so that it works with the Java server.

My 1st problem is that because this C++ client was written a while ago, the Visual C++ 2010 is saying that the project is out of date.
I tried reading through forums for help with that and each was very specific to each case. I tried a few things suggested, but still no luck.

Below I'll post the C++ client and later I'll post the Java server/client.

Anyone interested in helping me out with this? It'd be much appreciated, I've done stuff on C++ but nothing like network sockets, so I'm a little confused.

Thanks ahead of time.
Here's the C++ client I have:
---------------------------------------
#include <winsock2.h>
#include <windows.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <conio.h>

int main(int argv, char** argc){

int host_port= 1101;
char* host_name="127.0.0.1";

//Initialize socket support WINDOWS ONLY!
unsigned short wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 || ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )) {
fprintf(stderr, "Could not find useable sock dll %d\n",WSAGetLastError());
goto FINISH;
}


int hsock;
int * p_int ;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if(hsock == -1){
printf("Error initializing socket %d\n",WSAGetLastError());
goto FINISH;
}

p_int = (int*)malloc(sizeof(int));
*p_int = 1;
if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 )||
(setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
printf("Error setting options %d\n", WSAGetLastError());
free(p_int);
goto FINISH;
}
free(p_int);

struct sockaddr_in my_addr;

my_addr.sin_family = AF_INET ;
my_addr.sin_port = htons(host_port);

memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = inet_addr(host_name);


if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == SOCKET_ERROR ){
fprintf(stderr, "Error connecting socket %d\n", WSAGetLastError());
goto FINISH;
}


char buffer[1024];
int buffer_len = 1024;
int bytecount;

int c;
memset(buffer, '\0', buffer_len);

for(char* p=buffer ; (c=getch())!=13 ; p++){
printf("%c", c);
*p = c;
}

if( (bytecount=send(hsock, buffer, strlen(buffer),0))==SOCKET_ERROR){
fprintf(stderr, "Error sending data %d\n", WSAGetLastError());
goto FINISH;
}
printf("Sent bytes %d\n", bytecount);

if((bytecount = recv(hsock, buffer, buffer_len, 0))==SOCKET_ERROR){
fprintf(stderr, "Error receiving data %d\n", WSAGetLastError());
goto FINISH;
}
printf("Recieved bytes %d\nReceived string \"%s\"\n", bytecount, buffer);

closesocket(hsock);

FINISH:
;
}
Wow, no replies, hope people start looking at this thread

Anyway, the first thing I did was to change the host port since the Java application was using the port "1234", so I changed it to that.

Next, I added a piece of code to find the computer's IP address and use that instead of the internal IP (127.0.0.1), because the Java client (will run parallel to the C++ client) has at the beginning a part where it looks for the IP.

----------------------

The problem is still the same though, because this code is oldish, when I try to run it on VC++ 2010, it says that the code is out of date and I can't figure out how to get around that, so I can't check to see if the alterations work. Any ideas on how I can get rid of this msg and run the code? I tried suggestions from people that had the same problem, but none of them worked, I think it's a problem more particular to this code itself. Any suggestions?

thank you
This is not C++ code, it's C code. What's worse, it's shitty C code.
You either should try to compile it with a C compiler or look for a C++ code snippet.
cometahalley: I'm not clear on what the problem is.
Hi,
it should be no problem to compile c-code with a c++-compiler and most of the commands for the sockets are still used so i don't know why it doesn't work.
But I've written a new socket class in c++, it isn't fully completed, but it should be enough for your problem. I've written a short example of a http-client using that class, that you can understand how it works. I hope it solves your problem:

(you need to link the library wininet.lib)

win_socket_class-test.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#ifndef HEADER_WIN_SOCKET_CL
#define HEADER_WIN_SOCKET_CL

#define BUFFER_SIZE                 102400
#define BUFFER_MAX                  1000000

#define SOCKET_INACTIVE             0x00
#define SOCKET_OPEN_DONE            0x01
#define SOCKET_OPEN_SUCCESS         0x02
#define SOCKET_CONNECTED_DONE       0x04
#define SOCKET_CONNECTED_SUCCESS    0x08
#define SOCKET_SEND_DONE            0x10
#define SOCKET_SEND_SUCCESS         0x20
#define SOCKET_RECV_DONE            0x40
#define SOCKET_RECV_SUCCESS         0x80

#define SOCKET_PROTOCOL_TCP         0x1
#define SOCKET_PROTOCOL_UDP         0x2

#define CHECK_OPEN_DONE(status)            (status & SOCKET_OPEN_DONE)
#define CHECK_OPEN_SUCCESS(status)         ((status & SOCKET_OPEN_SUCCESS) >> 1)
#define CHECK_CONNECTED_DONE(status)       ((status & SOCKET_CONNECTED_DONE) >> 2)
#define CHECK_CONNECTED_SUCCESS(status)    ((status & SOCKET_CONNECTED_SUCCESS) >> 3)
#define CHECK_SEND_DONE(status)            ((status & SOCKET_SEND_DONE) >> 4)
#define CHECK_SEND_SUCCESS(status)         ((status & SOCKET_SEND_SUCCESS) >> 5)
#define CHECK_RECV_DONE(status)            ((status & SOCKET_RECV_DONE) >> 6)
#define CHECK_RECV_SUCCESS(status)         ((status & SOCKET_RECV_SUCCESS) >> 7)

    #include <string>
    #include <windows.h>
    #include <winsock2.h>
    #pragma comment(lib, "wininet.lib")

    using namespace std;


    typedef struct Buffer
    {
        char *data;
        int size;
    };


    class MainWSA
    {
        private:
            WSADATA wsa;
    
        public:
            bool Start (BYTE majorVers, BYTE minorVers);
            bool Clean ();
    };


    class Socket
    {
        protected:
            /* socket ID */
            SOCKET socket;


            /* parameters for socket-open */
            int socketOpenType, socketOpenProtocol;

            /* socket settings */
            int protocol;                                                    //use SOCKET_PROTOCOL_...           
            unsigned short port;
            
            unsigned int status;                                            //use CHECK_... macros to get infos

            /* buffer(s) for socket */
            Buffer buffer;
            int receivedBytes;
            string textBuffer;

        public:
            
            bool checkSockOpen ();
            bool successSockOpen ();
            
            unsigned int getStatus ();
            
            //convert
            string getIPByHostname (string Hostname);
            string getHostnameByIP (string IP);

            string ConvertIPToString (in_addr * addr);
            in_addr ConvertIPToIn_addr (string addr);


            //set-get
            bool setProtocol (int protocol);
            int getProtocol ();


            bool setPort (unsigned short port);
            unsigned short getPort ();
            
            //main functions
            bool Open ();
            bool Open (int protocol);
            bool Open (int socketType, int socketProtocol);
            
            
            virtual bool Receive () = 0;
            virtual bool ReceiveText () = 0;

            virtual bool Send (char * data, int size) = 0;
            virtual bool SendText (string data) = 0;        

            Buffer getBuffer ();
            int getReceivedBytes ();
            string getStrBuffer ();
            bool clearBuffer ();
            bool clearStrBuffer ();

            bool Close ();
    };

    class ClientSocket : public Socket
    {
        private:
            in_addr IP;
            string IPStr, hostname;
      
        public:
            ClientSocket ();
            ~ClientSocket ();

            unsigned int getStatus ();

            bool checkSockConnected ();
            bool successSockConnected ();

            bool setHostByIP (string IP);
            bool setHostByName (string name);

            string getIPStr ();
            in_addr getIP ();
            string getHostname ();


            //main functions
            bool Connect ();
            bool Connect (string IP, unsigned short port);
            bool Connect (int protocol, string IP, unsigned short port);

            bool Receive ();
            bool ReceiveText ();

            bool Send (char * data, int size);
            bool SendText (string data);
    };
#endif 


main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <cstdlib>
#include <iostream>
#include <string>
#include "win_socket_class-test.h"



using namespace std;      


int main(int argc, char *argv[])
{
    ClientSocket socket1;
    MainWSA WSA;
    if(WSA.Start(2, 2))
    {
        cout<<"Error: Could not Start WSA"<<endl;
        system("PAUSE");
        return EXIT_FAILURE;
    }
    
    string host = "www.wikipedia.org";
    string ip = "91.198.174.232";                       //IP of wikipedia, you could also use socket1.setHostByName("www.wikipedia.org");
    
    socket1.Open(SOCKET_PROTOCOL_TCP);
    socket1.setPort(80);                                //http port
    socket1.setHostByIP(ip);
    
    
    cout<<endl<<"Connecting to:"<<socket1.getIPStr()<<"...";
    
    socket1.Connect();
    
    cout<<endl<<"Sending Request:"<<endl<<endl;
    string req = "GET / HTTP/1.1\nHost: " + host + "\n\n";
    
    cout<<endl<<req<<endl<<endl<<"Receiving Response...";
    
    
    
    socket1.SendText(req);                               //Sends the request
    socket1.ReceiveText();                               //receives the response text
    
    cout<<endl<<"Response:"<<endl<<socket1.getStrBuffer()<<endl<<endl<<"Bytes: "<<socket1.getReceivedBytes()<<endl<<endl;
    //.getStrBuffer returns the receives text; .getReceivesBytes the number of bytes received
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}


win_socket_class-test.cpp is in the second post.

hi,

here's the second part:

(win_socket_class-test.cpp - part1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#include "win_socket_class-test.h"

using namespace std;


ClientSocket::ClientSocket()
{
    this->socketOpenType = SOCK_STREAM;
    this->socketOpenProtocol = 0;
    
    this->socket = 0;
    
    
    this->protocol = 0;
    this->port = 0;
    
    this->buffer.size = 0;
    
    this->status = SOCKET_INACTIVE;
    
    this->IP.s_addr = 0;
    this->IPStr = "";
    this->hostname = "";
    
    this->buffer.size = 0;
    this->receivedBytes = 0;
    this->textBuffer = "";    
}

ClientSocket::~ClientSocket()
{
    this->Close();
}



unsigned int Socket::getStatus ()
{
    return this->status;
}


bool Socket::checkSockOpen ()
{
    return CHECK_OPEN_DONE(this->status);
}

bool Socket::successSockOpen ()
{
    return CHECK_OPEN_SUCCESS(this->status);
}

bool ClientSocket::checkSockConnected ()
{
    return CHECK_CONNECTED_DONE(this->status);
}

bool ClientSocket::successSockConnected ()
{
    return CHECK_CONNECTED_SUCCESS(this->status);
}





/*  Conversions  -  START  */

string Socket::getIPByHostname (string hostname)
{
    hostent* h = gethostbyname(hostname.c_str());
    in_addr addr =  *(struct in_addr*) h->h_addr;
    string returnStr(inet_ntoa(addr));
    return returnStr;
}

string Socket::getHostnameByIP (string IP)
{
    in_addr address;
    address.s_addr = inet_addr(IP.c_str());
    if(address.s_addr == INADDR_NONE)
    {
        return "";
    }
    hostent * h = gethostbyaddr((char *)&address, 4, AF_INET); 
    string returnStr(h->h_name);
    return returnStr;
}


string Socket::ConvertIPToString (in_addr * addr)
{
    string returnStr(inet_ntoa(*addr));
    return returnStr;
}

in_addr Socket::ConvertIPToIn_addr (string addr)
{
    in_addr returnStruct;
    returnStruct.s_addr = inet_addr(addr.c_str());
    return returnStruct;
}
/*  Conversions  -  END  */


/*  Set/Get  -  START  */
             
bool Socket::setProtocol (int protocol)
{
    if(CHECK_OPEN_DONE(this->status) == 0)
    {
        this->protocol = protocol;
        switch(protocol)
        {
            case SOCKET_PROTOCOL_TCP:
                this->socketOpenType = SOCK_STREAM;
                this->socketOpenProtocol = IPPROTO_TCP; 
                break;
            default:
                this->socketOpenType = SOCK_STREAM;
                this->socketOpenProtocol = 0;
        }
        return FALSE;
    }
    return TRUE;
}

int Socket::getProtocol ()
{
    return this->protocol;
}

             
bool Socket::setPort (unsigned short port)
{
    if(CHECK_CONNECTED_DONE(this->status) == 0)
    {
        this->port = port;
        return FALSE;
    }
    return TRUE;
}

unsigned short Socket::getPort ()
{
    return this->port;
}
             

bool ClientSocket::setHostByIP (string IP)
{
     if(CHECK_CONNECTED_DONE(this->status) == 0)
     {
         this->IPStr = IP;
     
         this->IP.s_addr = inet_addr((const char *)IP.c_str());
         this->hostname = "";
         return FALSE;
    }
    return TRUE;
}

bool ClientSocket::setHostByName (string name)
{
     if(CHECK_CONNECTED_DONE(this->status) == 0)
     {
         this->hostname = name;
         hostent * h = gethostbyname(hostname.c_str());
         this->IP = *(struct in_addr*) h->h_addr;
         string str(inet_ntoa(this->IP));
         this->IPStr = str;
         
         return FALSE;
     }
     return TRUE;
}


string ClientSocket::getIPStr ()
{
    return this->IPStr;
}

in_addr ClientSocket::getIP ()
{
    return this->IP;
}

string ClientSocket::getHostname ()
{
    return this->hostname;
}



bool Socket::Open ()
{
    if(CHECK_OPEN_DONE(this->status) == 0)
    {
        int socketValue = ::socket(AF_INET, this->socketOpenType, this->socketOpenProtocol);
        if(socketValue != -1);
        {
            this->socket = socketValue;
            this->status |= SOCKET_OPEN_DONE | SOCKET_OPEN_SUCCESS;
            return FALSE;
        }
    }
    return TRUE;
}

bool Socket::Open(int protocol)
{
     this->setProtocol(protocol);
     return this->Open();
}


bool Socket::Open(int socketType, int socketProtocol)
{
     this->setProtocol(0);
     this->socketOpenType = socketType;
     this->socketOpenProtocol = socketProtocol;
     return this->Open();
}



bool ClientSocket::Connect ()
{
    if(CHECK_OPEN_DONE(this->status) == 1 && CHECK_CONNECTED_DONE(this->status) == 0)
    {
         sockaddr_in addr;
         addr.sin_family = AF_INET;
         addr.sin_addr.s_addr = this->IP.s_addr;
         addr.sin_port = htons(this->port);
         if(connect(this->socket, (const sockaddr*)&addr, sizeof(addr)) != -1)
         {
             this->status |= SOCKET_CONNECTED_DONE | SOCKET_CONNECTED_SUCCESS;
             return FALSE;
         }
         return TRUE;         
    }
}

bool ClientSocket::Connect (string IP, unsigned short port)
{
    this->setPort(port);
    this->setHostByIP(IP);
    this->Connect();
}

bool ClientSocket::Connect (int protocol, string IP, unsigned short port)
{
    this->setProtocol(protocol);
    this->Connect(IP, port);
}



bool ClientSocket::Receive ()
{
    this->status &= ~SOCKET_RECV_DONE;
    this->clearBuffer();
    if(CHECK_CONNECTED_DONE(this->status) == 1)
    {
        char buffer[BUFFER_MAX];
        int bytesRecv = 0, resultRecv = 0;
        do
        {
            resultRecv = recv(this->socket, &buffer[bytesRecv], BUFFER_SIZE - 1, 0);
            bytesRecv += resultRecv;
        }
        while(resultRecv > 0 && bytesRecv < BUFFER_MAX);
        if(resultRecv != -1)
        {
            this->receivedBytes = bytesRecv;
            this->buffer.size = bytesRecv;
            this->buffer.data = buffer;
            this->status |= SOCKET_RECV_DONE | SOCKET_RECV_SUCCESS;
            return FALSE; 
        }
    }
    this->status |= SOCKET_RECV_DONE;
    this->status &= ~SOCKET_RECV_SUCCESS;
    return TRUE;
}



bool ClientSocket::ReceiveText ()
{
    this->status &= ~SOCKET_RECV_DONE;
    char buffer[BUFFER_MAX];
    int bytesRecv = 0, resultRecv = 0;
    do
    {
        resultRecv = recv(this->socket, &buffer[bytesRecv], BUFFER_SIZE - 1, 0);
        bytesRecv += resultRecv;
    }
    while(resultRecv > 0 && bytesRecv < BUFFER_MAX);
    if(resultRecv != -1)
    {
        buffer[bytesRecv] = '\0';
        this->receivedBytes = bytesRecv;
        string strBuf(buffer);
        this->textBuffer = strBuf;
        this->status |= SOCKET_RECV_DONE | SOCKET_RECV_SUCCESS;
        return FALSE;
    }
    this->textBuffer = "";
    this->status |= SOCKET_RECV_DONE;
    this->status &= ~SOCKET_RECV_SUCCESS;
    return TRUE;
}
hi,
and here's the last part

(win_socket_class-test.cpp - part2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
bool ClientSocket::Send (char * data, int size)
{
    this->status &= ~SOCKET_SEND_DONE;
    if(CHECK_CONNECTED_DONE(this->status) == 1)
    {
        int bytesSent = 0, resultSend = 0;
        do
        {
            int tempSize = ((size - bytesSent) > BUFFER_SIZE ? BUFFER_SIZE : size - bytesSent);
            resultSend = send(this->socket, &data[bytesSent], tempSize, 0);
            bytesSent += resultSend;
        }
        while(bytesSent < size && resultSend != -1);
        
        if(resultSend != -1)
        {
            if(bytesSent == size)
            {
                this->status |= SOCKET_SEND_DONE | SOCKET_SEND_SUCCESS;
                return FALSE;
            }
        }
    }
    this->status |= SOCKET_SEND_DONE;
    this->status &= ~SOCKET_SEND_SUCCESS;
    return TRUE;
}


bool ClientSocket::SendText (string data)
{
    this->status &= ~SOCKET_SEND_DONE;
    if(CHECK_CONNECTED_DONE(this->status) == 1)
    {
        char * textBuffer;
        textBuffer = (char *)data.c_str();
            Buffer buffer;
            buffer.size = strlen(textBuffer);
            buffer.data = textBuffer;
            Buffer * pBuffer = &buffer;
            if(!this->Send(textBuffer, strlen(textBuffer)))
            {
                this->status |= SOCKET_SEND_DONE | SOCKET_SEND_SUCCESS;
                return FALSE;
            }
    }
    this->status |= SOCKET_SEND_DONE;
    this->status &= ~SOCKET_SEND_SUCCESS;
    return TRUE;    
}



Buffer Socket::getBuffer ()
{
    return this->buffer;
}

int Socket::getReceivedBytes ()
{
    return this->receivedBytes;
}

string Socket::getStrBuffer ()
{
    return this->textBuffer;
}


bool Socket::clearBuffer ()
{
    this->buffer.size = 0;
    this->receivedBytes = 0;
}

bool Socket::clearStrBuffer ()
{
    this->textBuffer = "";
}


bool Socket::Close()
{
    if(CHECK_OPEN_DONE(this->status) == 1)
    {
        if(closesocket(this->socket) != -1)
        {
            this->socket = 0;
            this->status = SOCKET_INACTIVE;
            return FALSE;
        }
    }
    return TRUE;
}


bool MainWSA::Start (BYTE majorVers, BYTE minorVers)
{
    if (WSAStartup(MAKEWORD(majorVers, minorVers), &this->wsa))
    {
        return TRUE;
    }
    return FALSE;
}

bool MainWSA::Clean ()
{
    if(WSACleanup() == 0)
    {
        return FALSE;
    }
    return TRUE;
}
"This is not C++ code, it's C code. What's worse, it's shitty C code.
You either should try to compile it with a C compiler or look for a C++ code snippet."

That explains a lot, however, I'd still expect it to compile in VC++ 2010. I'll look for better code.
Hi "philipjan09"

Thank you very much, I'll copy and try to run it a little later today.

If I were to use this code as base to connect to a java server later I'd still have to implement a JNI to make that work right?

sorry, I don't have too much experience in this area.

Thank you again
You don't need JNI for this. You are accessing the Java code by communicating through a socket rather than JNI .
Topic archived. No new replies allowed.