Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Java and .Net interop using Sockets

3.00/5 (10 votes)
12 Sep 20054 min read 1   999  
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)

Introduction

<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 java.net 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>

<o:p> 

<o:p> 

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

<o:p> 

Server Side code<o:p>

<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 !!

<o:p> 

<o:p> 

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

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

                        server_socket.getLocalPort());<o:p>

         <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>

<o:p> 

<o:p> 

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

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

<o:p> 

<o:p> 

<o:p> 

Client Side code<o:p>

<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.

<o:p> 

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>

(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);<o:p>

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

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

<o:p> 

                 socket.Connect(remoteEP);<o:p>

<o:p> 

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

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

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

<o:p> 

                 socket.Connect(remoteEP);<o:p>

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

                 Receive(socket);<o:p>

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

                 while(true)<o:p>

                 {<o:p>

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

                       <o:p>

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

                       if(lineToBeSent.Equals("."))<o:p>

                       {<o:p>

                             socket.Close();<o:p>

                             break;<o:p>

                       }<o:p>

                       //output.WriteLine(lineToBeSent);\<o:p>

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

                       socket.Send(encoding.GetBytes(lineToBeSent));<o:p>

                 } <o:p>

<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.

 

License

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