Solved

How to communicate between java and C#.NET using sockets?

Posted on 2008-09-29
13
2,458 Views
Last Modified: 2013-11-24
Hi, I need to connect a J2ME client to a C# server to send and receive some data.
I'm using sockets and can correctly connect.
My question is if is there a way I can send a structure between da java client and the c# server.
I will need to send several structures from the client to the server.
I do not want to use webservices as it requires to establish connection every time and because of the overhead.
All data (several structures) will be periodically sent to the server at the same time using one socket allowing to maintain the connection for sending all data.
The structure consists of some integers and a stream of bytes which contains sound previously recorded.
I could use xml and parse it but is there another and better way?
Thanks and regards.

Joao
0
Comment
Question by:jcarneiro
  • 4
  • 4
  • 2
  • +2
13 Comments
 
LVL 5

Expert Comment

by:jose_juan
Comment Utility
Hi,

the best way are WebService (over SOAP), the proccess are simple

1. define the class struct for serialization (all data struct that you need)
2. define only one method on your webservice (put and/or get information)

    public my_struct Get( credentials ) { ... return struct; }

   public bool Put( credentials, my_struct ) { ... use my_struct parameter; ... return true; }

3. the server (when Get) or client (when Put) populate the entire my_struct data and send all information (use array for multiple registers)

and that's all! the SOAP layer will send all struct for you.
0
 

Author Comment

by:jcarneiro
Comment Utility
Hi, thanks for your suggestion.
As I said I do not intend to use webservices as I need to minimize the traffic between client and server.
I am avoiding webservices both for the overhead and the connection/disconnection for every data I send. This is both energy and bandwidth consuming.
Because I will be sending all the data during the same period sockets make more sense although I agree webservices would be much easier.
I'm currently sending data through the socket in xml and parsing it at the other end but this is also very consuming because of the xml tags. I know of the existence of WOX a solution for serializing/deserializing objects in xml with java and c# I'm not using it. There is also IIOP for java rmi and .net remoting but don't know if anything is applicable and works in J2ME and my scenario as I'm not developing a system with remote objects just intend to send data between the two platforms.


Current solution: I think I will end up defining a low level protocol sending only the data separated by special bit sequence  and with some crc checking. Will also try to compress the data to minimize bandwidth usage even further.

Regards,

Joao
0
 
LVL 5

Expert Comment

by:jose_juan
Comment Utility
Hi,

but, you don't need connect/disconnect for each data!, you only send ALL data at once.

If you like, then do it (but not have advantage):

1. generate data at origin (client or server).
2. serialize all your structure data into xml format.
3. compress data.
4. send to other system.
5. deserialize data and use it.

NOTE: your petition are "send a structure (typical class java/C#)" the serialization process (in SOAP is transparent) make it for you.
NOTE: when you send data on SOAP over HTTP you can configure your systems for autocompress autodecompress data.

These process is the SAME than using SOAP but more effort for you.

Good luck!
0
 
LVL 17

Expert Comment

by:CSecurity
Comment Utility
for ex. you have a structure like this:
struct :
{
string name;
long int studentID;
string birth_date;
}

so, you can send them in this way:
<name>Bill Gates</name><stdID>8238392</stdID><brtdate>2/12/1984</brtdat>
and after receiving, you can parse it and set all of data to your strucure.
regards...
0
 
LVL 5

Expert Comment

by:jose_juan
Comment Utility
Obviously, but this job is done by SOAP implementations...
Instead direct translation and parsing, USE serialization! (I think is much better)
0
 

Accepted Solution

by:
jcarneiro earned 0 total points
Comment Utility
Thank you very much for your suggestions.
I ended up defining my own messages.
I just create a socket connection send a first int (4Bytes) containing the length of the message I will send and then send the actual message. I have only one field with variable length so I'm able to define my own message like this:

---------------------------------------------------------------------------------------------------------------------------
| length (4Bytes) | field1 (4Bytes) | field2 (4Bytes) | field3 (4Bytes) | field4 (variable size) | crc (4Bytes |
---------------------------------------------------------------------------------------------------------------------------

This allows me to save lots of traffic from xml tags. I will also try to find an algorithm for byte[] compression. Using this protocol I can send all messages with the above structure using the same socket connection.
Regards
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 5

Expert Comment

by:jose_juan
Comment Utility
Ok, jcarneiro, this is the trivial solution and the worst.

If your application are small, propietary and you don't think upgrade on future, this is a valid alternative.

If you think share your code or upgrade your program I recommend to you a better and standard method.

For compress a byte array you can find huge amount of examples and algorithms.

If you have a problem, ask.

Good luck!
0
 
LVL 1

Expert Comment

by:mdw233
Comment Utility
hey jcarneiro,

Do you have sample code on how you are using sockets to sommunicate between java and C#?
0
 

Author Comment

by:jcarneiro
Comment Utility
You only have to create a socket at each and read byte[] normally.
You should check .net c# socket examples. I don't have the urls but this code was taken and adapted from there. I provide you a c# server receiving connections and reading a 32bit int from the socket, and som parts of a java client using a socket to connect to the server.
Hope this can help you any questions write me back
/*C#SERVER*/

try

            {

                // Create the listening socket...

                m_mainSocket = new Socket(AddressFamily.InterNetwork,

                                          SocketType.Stream,

                                          ProtocolType.Tcp);

                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);

                // Bind to local IP Address...

                m_mainSocket.Bind(ipLocal);

                // Start listening...

                m_mainSocket.Listen(4);

                // Create the call back for any client connections...

                m_mainSocket.BeginAccept(new AsyncCallback(onClientConnect), null);

            }

            catch (SocketException se)

            {

                System.Console.WriteLine(se.Message);

            }
 
 

private static void onClientConnect(IAsyncResult asyn)

        {

            try

            {

                // Here we complete/end the BeginAccept() asynchronous call

                // by calling EndAccept() - which returns the reference to

                // a new Socket object

                m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);

                // Let the worker Socket do the further processing for the 

                // just connected client

                WaitForData(m_workerSocket[m_clientCount]);

                // Now increment the client count

                ++m_clientCount;

                // Display this client connection as a status message on the GUI	

                String str = String.Format("Client # {0} connected", m_clientCount);

                System.Console.WriteLine(str);
 

                // Since the main Socket is now free, it can go back and wait for

                // other clients who are attempting to connect

                m_mainSocket.BeginAccept(new AsyncCallback(onClientConnect), null);

            }

            catch (SocketException se)

            {

                System.Console.WriteLine(se.Message);

            }

        }
 
 

public class SocketPacket

        {

            public System.Net.Sockets.Socket m_currentSocket;

            public byte[] dataBuffer;

        }
 

        // Start waiting for data from the client

        public static void WaitForData(System.Net.Sockets.Socket soc)

        {

            try

            {

                if (pfnWorkerCallBack == null)

                {

                    // Specify the call back function which is to be 

                    // invoked when there is any write activity by the 

                    // connected client

                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);

                }

                SocketPacket theSocPkt = new SocketPacket();

                theSocPkt.m_currentSocket = soc;

                theSocPkt.dataBuffer = new byte[4];
 

                // Start receiving any data written by the connected client

                // asynchronously

                soc.BeginReceive(theSocPkt.dataBuffer, 0,

                                   theSocPkt.dataBuffer.Length,

                                   SocketFlags.None,

                                   pfnWorkerCallBack,

                                   theSocPkt);

            }

            catch (SocketException se)

            {

                System.Console.WriteLine(se.Message);

            }
 

        }
 
 
 
 
 

        // This the call back function which will be invoked when the socket

        // detects any client writing of data on the stream

        public static void OnDataReceived(IAsyncResult asyn)

        {

            try

            {

                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                

                int iRx = 0;
 

                // Complete the BeginReceive() asynchronous call by EndReceive() method

                // which will return the number of characters written to the stream 

                // by the client

                iRx = socketData.m_currentSocket.EndReceive(asyn);
 

                //Reading a 4 bytes from the socket into a 32bit var

                int len = System.BitConverter.ToInt32(socketData.dataBuffer, 0);
 

// Continue the waiting for data on the Socket

                WaitForData(socketData.m_currentSocket);

            }

            catch (ObjectDisposedException)

            {

                System.Console.WriteLine("\nOnDataReceived: Socket has been closed\n");

            }

            catch (SocketException se)

            {

                System.Console.WriteLine(se.Message);

            }

            catch (Exception ex)

            {

                System.Console.WriteLine("OnDataReceived: " + ex.Message);

            }

        }
 
 
 

/*JAVA client*/

openParm = "socket://" + destHost + ":" + destPort+ ";" + connProfile;
 

private boolean openGPRSConnection(){

        boolean result = true;

        

        try{

            sc = (SocketConnection) Connector.open(openParm);

            is = sc.openInputStream();

            os = sc.openOutputStream();

        } catch(IOException ioe) {

            System.out.println("openGPRSConnection(): " + ioe);

            result = false;

        }
 

        

        return result;

    }
 
 
 

 if(openGPRSConnection()){

            

            

            

            for (;;) {

                try {

byte[] mesg = createMessage();

                    System.out.println(arrMesg);

                    os.write(mesg);

 } catch(IOException e) {

                    System.out.println("startApp(): " + e);

                    closeGPRSConnection();

}

}

}

Open in new window

0
 
LVL 1

Expert Comment

by:mdw233
Comment Utility
Hey jcarneiro,

Thanks for your help!  I actually found that same exact example and am using it now, but I have run into issues where some of the data seems to get lost on the way. Have you experienced this issue at all?
0
 

Author Comment

by:jcarneiro
Comment Utility
Hi, haven't experienced any data loss.
Confirm you are using a TCP socket. UDP does not guarantee all packet delivery and that could be your problem.
0
 

Expert Comment

by:andyfenna
Comment Utility
Serialize the dataset to xml( string) an convert it at the web service using the readxmll() member
0
 

Expert Comment

by:andyfenna
Comment Utility
BTW all data set  rowset data is lost thr conersion hweva if you know the moodifiticatiin the type del/mod/add then send as a enum and control it programattically


Just my ten bob
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
C# code editing and collaboration 3 39
Create XML 5 30
fomat Json objects 6 15
Different Delete Messages 7 10
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This is about my first experience with programming Arduino.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now