Click here to Skip to main content
12,893,452 members (55,958 online)
Click here to Skip to main content
Add your own
alternative version


24 bookmarked
Posted 12 Sep 2005

Java and .Net interop using Sockets

, 12 Sep 2005
Rate this:
Please Sign up or sign in to vote.
Java and .Net interop using Sockets. Article explains a bit at both ends that will allow passing of primitive data between a Java socket server and C# client(s)
<!-- Article Starts - DO NOT ADD HTML/BODY START TAGS-->


<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p>All About sockets (well little actually)

<SPAN style="FONT-SIZE: 10pt">URLs and <SPAN style="FONT-SIZE: 10pt">URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application. <o:p>

In client-server applications, the server provides some service, such as processing database queries or sending out current stock prices. The client uses the service provided by the server, either displaying database query results to the user or making stock purchase recommendations to an investor. The communication that occurs between the client and the server must be reliable. That is, no data can be dropped and it must arrive on the client side in the same order in which the server sent it. <o:p>

TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet use to communicate with each other. To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. To communicate, the client and the server each reads from and writes to the socket bound to the connection. <o:p>

What Is a Socket?<o:p>

A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively. <o:p>

Reading from and Writing to a Socket<o:p>

This page contains a small example that illustrates how a client program can read from and write to a socket. <o:p>

Writing a Client/Server Pair<o:p>

The previous page showed an example of how to write a client program that interacts with an existing server via a Socket object. This page shows you how to write a program that implements the other side of the connection--a server program. <o:p>



Ok so much for the Socket basics …now lets understand a bit of code……..


Server Side code<o:p>


So  the server  side is obviously coded in Java. Don’t ask me why coz it’s just so. So in the below code the funda is that the new socket connection is created and the input and output buffers are  initiated to new input and output buffers which will be under your control !!



server_socket = new ServerSocket(port);<o:p>

         System.out.println("Server waiting for client on port " +<o:p>



         // server infinite loop<o:p>

         while(true) {<o:p>

           Socket socket = server_socket.accept();<o:p>

           System.out.println("New connection accepted " +<o:p>

                          socket.getInetAddress() +<o:p>

                          ":" + socket.getPort());<o:p>



    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));<o:p>

    output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));<o:p>




Client Side code<o:p>


Client side is coded in C#. So here is a code snippet. A very rudimentary client.  

Ok let me point you to the important sections in the code.


So the below piece of code is the creation of the actual socket connection. . Attributes like the protocol,IP address of the server are to be provided. Also note that I have personally used the port 1500 which is not a good practice. By general convention you should used a free port (like 8080 …etc). Anyway that’s unto the ultimate users of this code ….if any ;)….

socket = new System.Net.Sockets.Socket<o:p>


                 System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(""); <o:p>

                 System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd,1500);<o:p>




socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);<o:p>

                 System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(""); <o:p>

                 System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd,1500);<o:p>



                 //Async Read form the server side<o:p>


                 //new System.Net.Sockets.TcpClient(server, port);<o:p>



                       lineToBeSent = System.Console.ReadLine();<o:p>


                       // stop if input line is "."<o:p>







                       //System.Net.Sockets.NetworkStream tempstream = socket.GetStream();<o:p>


                 } <o:p>



And walla……..its done ……you can pass primitive data between the client and the server. But I have not gotten to Objects or structures yet. I will update this article once that is done.



This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Anand Manikiam
Web Developer
France France
.Net programmer ......./ Dum ass Wink | ;)

You may also be interested in...


Comments and Discussions

General[Message Deleted] Pin
it.ragester2-Apr-09 21:52
memberit.ragester2-Apr-09 21:52 
GeneralHelp: OutOfMemoryError on server on receiving data Pin
fpuspitasari10-Sep-06 17:25
memberfpuspitasari10-Sep-06 17:25 
Hi, I have a similar application with the one you wrote, a C# client and java based server. THe socket connection can be established well. However,I experience problem when I tried to exchange data. The server throws java.lang.OutOfMemoryError when the client sent data to server. I don't think the server has problem with memory heap since this server can also communicate with other java based client without this kind of error. I wonder whether this is something related to interop issue? Or perhaps i've done thing incorrectly in the client?

here is the code snippet from my client:
//Data buffer for incoming data.
byte[] bytes = new byte[1024];

// Connect to a remote device.
// Establish the remote endpoint for the socket.
// The name of the
Console.WriteLine("Try to access server");
IPHostEntry ipHostInfo = Dns.Resolve(myServerName);
//myServerName= server url
foreach(IPAddress ipad in ipHostInfo.AddressList)
this.setString(ipad.ToString() + " ");
IPAddress ipAddress = ipHostInfo.AddressList[0];

IPEndPoint remoteEP = new IPEndPoint(ipAddress,8085);

// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Sender = " + sender.ToString());

// Connect the socket to the remote endpoint. Catch any errors.

Console.WriteLine("Socket connected to {0}",
Console.WriteLine("Socket connected to "+ sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("Hello");

// Send the data through the socket.
for (int i = 0; i < msg.Length; i++)
int bytesSent = sender.Send(msg);

// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",

General5 from me Pin
Trance Junkie10-Apr-06 5:01
memberTrance Junkie10-Apr-06 5:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170424.1 | Last Updated 12 Sep 2005
Article Copyright 2005 by Anand Manikiam
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid