[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2577
  • Last Modified:

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

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
jcarneiro
Asked:
jcarneiro
  • 4
  • 4
  • 2
  • +2
1 Solution
 
jose_juanCommented:
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
 
jcarneiroAuthor Commented:
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
 
jose_juanCommented:
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
CSecurityCommented:
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
 
jose_juanCommented:
Obviously, but this job is done by SOAP implementations...
Instead direct translation and parsing, USE serialization! (I think is much better)
0
 
jcarneiroAuthor Commented:
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
 
jose_juanCommented:
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
 
mdw233Commented:
hey jcarneiro,

Do you have sample code on how you are using sockets to sommunicate between java and C#?
0
 
jcarneiroAuthor Commented:
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
 
mdw233Commented:
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
 
jcarneiroAuthor Commented:
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
 
andyfennaCommented:
Serialize the dataset to xml( string) an convert it at the web service using the readxmll() member
0
 
andyfennaCommented:
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 4
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now