Socket Communication--c++ server-side and Java client

Source: Internet
Author: User

in a word, C + + and Java through the socket for communication, data transmission, by sending a "byte stream" can be.

Bytes are common to C + + and Java, but the process of transmission has many problems to pay attention to, I have to find out the process, some information, do some sorting.

Do not understand C + + socket programming, you can read this blog:

Linux under: Socket communication (Linux, C + + language): http://blog.csdn.net/giantpoplar/article/details/47657303

under Windows: Winsock: http://blog.csdn.net/giantpoplar/article/details/47657317

Do not understand Java socket programming, you can read this blog:

Java Socket communication:http://blog.csdn.net/giantpoplar/article/details/47657325

Do not understand the conversion of byte arrays and basic data types, you can read this blog

byte[] and shaping, floating-point data conversion-java Code : http://blog.csdn.net/giantpoplar/article/details/47657333

The following two ways may be taken when the server sends data to the client

Server-side Direct send struct

If you are sending a struct directly on the C + + side during programming, you need to cast the pointer of this struct to char*, which is transmitted by one byte

MSG message;retval = Send (Client, (char*) &message,sizeof (MSG), 0);

In this way, after the client receives the data, it needs to memory layout for C + + objectsThere is a simple understanding, likewise, if you do not understand, you can read this article: memory layout for simple C + + objects: http://blog.csdn.net/giantpoplar/article/details/47658679

In addition, if your server uses Java, to write an object in a objectoutputstream way, you need to understand the memory layout of the Java object, again, if you do not understand, you can read this: simple Java Object Memory layout : http:/ /blog.csdn.net/giantpoplar/article/details/47657377


The server side sends each member of the struct individually

Another way is not to put the entire structure of the entire past, but a variable sent past, when the server and the client side to know the sequence of these variables, one at a time to accept, which involves the conversion between the byte array and the basic data type.

At this point, notice whether the server and client integers are represented in the same way, are either big-endian or small-ended, and floating-point numbers indicate compliance with the IEEE 754 specification. Otherwise, the two sides to coordinate well, or floating point directly to the string, although it will bring efficiency loss, but can be unified together.

Both of these problems have shortcomings, first of all, the big-endian, the small end represents the potential error that may be caused.

The second is that if the struct contains pointers, the data it points to is not in the struct's instance, may be contrary to the user's idea, in which case the use of "serialization" may be a better choice, here to find a simple introduction http://www.infoq.com/cn /news/2014/06/flatbuffers.


Some of the problems I encountered

The server side sends the data at one time the size is not too large, for example, when I send a 538-byte msg, there is a transmission anomaly, I am normal test in this machine, no longer on the same machine when there will be a problem.

Note: The sending side and the receiver accept the same size of the data, such as 128 bytes at a time, accept also accept 128 bytes at a time, otherwise prone to loss of packets, sticky packets and other problems, data transmission anomalies;

Not too big, too big and prone to problems;

To be more reliable, you can define a protocol, each time the data is sent to include the length of the packet, check code and other information


Attached below is a program I wrote recently, basic skills can have, but not very perfect

Because my server and client are definitely small-ended mode storage integers, it's not considered the byte order of the transmission at the moment.

Writing a message class is a convenient way to put some methods in the future.

Java Client

Import Java.io.ioexception;import java.io.inputstream;import Java.io.objectinputstream;import Java.io.OutputStream ; Import Java.net.serversocket;import Java.net.socket;import Java.net.unknownhostexception;public class JavaClient{ public static void Main (string[] args) throws Unknownhostexception,ioexception, ClassNotFoundException {//clientsocket s = new Socket ("127.0.0.1", 8899); InputStream is = S.getinputstream (); byte msg[] = new Byte[536];while (is.read (msg, 0, 53 6) >-1) {Message m = new Message (msg); if (m.guesture!=0) System.out.println (m.guesture);}}} public class Message {float left_hand[] = new float[66];//left-hand joint data [X0 Y0 Z0 X1 Y1 Z1 ... X21 Y21 z21]float right_hand[] = new float[66];//right-hand joint data short left;//detect if left hand 1 is detected, 0 is not detected if short right;//detects right-hand short gues ture;//gesture Short alert_type;//warning type public Message (byte[] msg) {//Construct a Message object from a byte array for (int i=0; i<66; i++) {left_hand[ I] = byte2float (msg, A. i);} for (int i=0; i<66; i++) {Right_hand[i] = byte2float (msg,264 + 4 * i);} left = geTshort (msg, 528); right = Getshort (msg, 530); guesture = Getshort (msg, 532); Alert_type = Getshort (msg, 534);}                                                 Array order according to "Small End order" private float byte2float (byte[] B, int index) {//4 bytes to float int l;                                      L = b[index + 0];                                             L &= 0xFF;                       L |= ((long) B[index + 1] << 8);                                           L &= 0xFFFF;                      L |= ((long) B[index + 2] << 16);                                         L &= 0xFFFFFF;                      L |= ((long) B[index + 3] << 24);                    Return Float.intbitstofloat (L); } Private short Getshort (byte[] Bytes,int index) {//two bytes to short return (0xFF & bytes[index+0]) |      (0xff00 & (Bytes[index+1] << 8))); }  }

C + + Service side

#include <Windows.h> #include <iostream> #include <string.h> #pragma comment (lib, "Ws2_32.lib") # ifndef msg_#define msg_struct msg{pxcf32 left_hand[66];p xcF32 right_hand[66];p xcI16 left;pxci16 right;pxci16 guesture; PxcI16 alert_type;};/            /Message Structure #endifint main () {wsadata wsad;        Wsadata variable socket Server;        The server socket socket Client;        Client socket sockaddr_in Addrserv;        server address int retVal; return value//Initialize socket dynamic Library if (WSAStartup (Makeword (2, 2), &wsad)! = 0) {std::p rintf ("Initialize socket dynamic library failed!\n"); return 1;} Create Socket Server = socket (af_inet, Sock_stream, ipproto_tcp), if (Invalid_socket = = Server) {std::p rintf ("Create socket failed!\n"); WSACleanup ();//release socket resources; return-1;} Server socket Address addrserv.sin_family = Af_inet;addrserv.sin_port = Htons (8899); addrServ.sin_addr.s_addr = inaddr_any;// Bind socket RetVal = Bind (Server, (lpsockaddr) &addrserv, sizeof (sockaddr_in)), if (socket_error = = retVal) {std::p rintf ("    Bind socket failed!\n "); closesocket (Server); Close the socketCharacter WSACleanup (); Release a socket resource; return-1;}    Start Listening RetVal = Listen (server, 1), if (socket_error = = retVal) {std::p rintf ("Listener failed!\n"); closesocket (server);            Close socket WSACleanup (); Release a socket resource; return-1;} for (;;) {//Accept client request sockaddr_in Addrclient;int Addrclientlen = sizeof (addrclient); Client = Accept (Server, (sockaddr far*) &addrclient, &addrclientlen), std::p rintf ("Accept a socket\n"); if (    Invalid_socket = = client) {std::p rintf ("Accept client request failed!\n"); Continue;//closesocket (Server);            Close socket//wsacleanup (); Release a socket resource;//return-1;} Send client data while (true) {WaitForSingleObject (Full_sem, INFINITE);//down operation//waitforsingleobject (mutex, INFINITE);// Multiple consumers need to add a mutex to the semaphore msg message = Msgqueue[head];head = (head + 1)% Queue_length;//releasesemaphore (mutex, 1, NULL);//up Operation Relea Sesemaphore (Empty_sem, 1, NULL);//up operation retval = Send (Client, (char*) &message, sizeof (MSG), 0); if (Socket_error = =    RetVal) {std::p rintf ("Receive client request failed!\n");//closesocket (Server);    Close socket closesocket (Client); Close Socket BREak;//return-1;} Sleep (100);}    std::p rintf ("%s\n", buf);    Outputs the string from the client//exit//closesocket (Server);    Close socket closesocket (Client); Close Socket}closesocket (Server);            WSACleanup (); Release the socket resource; return 0;}


Description

This article was published by Giantpoplar in Csdn

Article Address http://blog.csdn.net/giantpoplar/article/details/47658929

Reproduced please retain this note


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Socket Communication--c++ server-side and Java client

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.