5,781,815 members and growing! (1,221 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » Cross Platform » General     Intermediate

Java and .Net interop using Sockets

By Anand Manikiam

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)
C#, VC7, C++, HTML, Java, Windows, .NET, .NET 1.1, NT4, Win2K, WinXPVS.NET2003, IE 5.5, Visual Studio, IE, Dev

Posted: 12 Sep 2005
Updated: 12 Sep 2005
Views: 23,036
Bookmarked: 14 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
10 votes for this Article.
Popularity: 3.00 Rating: 3.00 out of 5
3 votes, 30.0%
1
0 votes, 0.0%
2
2 votes, 20.0%
3
0 votes, 0.0%
4
5 votes, 50.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

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.

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.

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.

What Is a Socket?

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.

Reading from and Writing to a Socket

This page contains a small example that illustrates how a client program can read from and write to a socket.

Writing a Client/Server Pair

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.

 

 

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

 

Server Side code

 

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

         System.out.println("Server waiting for client on port " +

                        server_socket.getLocalPort());

        

         // server infinite loop

         while(true) {

           Socket socket = server_socket.accept();

           System.out.println("New connection accepted " +

                          socket.getInetAddress() +

                          ":" + socket.getPort());

 

 

    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

 

 

 

Client Side code

 

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

(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

                 System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("15.76.126.101");

                 System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd,1500);

 

                 socket.Connect(remoteEP);

 

socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

                 System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("15.76.126.101");

                 System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(ipAdd,1500);

 

                 socket.Connect(remoteEP);

                 //Async Read form the server side

                 Receive(socket);

                 //new System.Net.Sockets.TcpClient(server, port);

                 while(true)

                 {

                       lineToBeSent = System.Console.ReadLine();

                      

                       // stop if input line is "."

                       if(lineToBeSent.Equals("."))

                       {

                             socket.Close();

                             break;

                       }

                       //output.WriteLine(lineToBeSent);\

                       //System.Net.Sockets.NetworkStream tempstream = socket.GetStream();

                       socket.Send(encoding.GetBytes(lineToBeSent));

                 }

 

 

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

About the Author

Anand Manikiam


.Net programmer ......./ Dum ass Wink
Occupation: Web Developer
Location: France France

Other popular Cross Platform articles:

  • Introduction to Mono - Your first Mono app
    The first in a series of articles about Mono. This article explains how to install Mono and shows how to compile your first Cross Platform application.
  • MONO: an alternative for the .NET framework
    This article presents possibilities for development of .NET applications running on operating systems other than Windows, using the MONO platform. Advantages and challenges will be presented. Also presented are some common issues encountered while developing applications using the .NET technology.
  • Embed ActiveX controls inside Java GUI
    With this your Java projects can take advantage of ActiveX controls and Office documents such as spreadsheets, charts, calendars, word processors, specialized graphics, and many more.
  • Introduction to Mono - ASP.NET with XSP and Apache
    The second article in a series of articles about Mono. This article explains how to host and serve ASP.NET Web Applications and Web Services on Linux using XSP and Apache with the help of Mono.
  • Phalanger, PHP for .NET: Introduction for .NET developers
    Phalanger is a PHP language compiler for the .NET Framework which introduces PHP as a first-class .NET citizen.
Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralHelp: OutOfMemoryError on server on receiving datamemberfpuspitasari18:25 10 Sep '06  
General5 from mememberTrance Junkie6:01 10 Apr '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Sep 2005
Editor:
Copyright 2005 by Anand Manikiam
Everything else Copyright © CodeProject, 1999-2009
Java | Advertise on the Code Project