C# Chat: Part 2 – Building the Chat Server

Download this Visual Studio 2005 project Download the Chat Server Application project (Visual Studio 2005)

This is the second part of a tutorial that teaches you how to create a C# chat application. In Part 1 – Building the Chat Clientwe’ve looked at how to create the chat application that connects to a chat server, and here we now look at how to build the chat server.

The Chat Server

The Chat Server application is a tad more complex than the Chat Client application because it needs to hold information on all the connected clients, await for messages from each and send incoming messages to all. I commented all the code so hopefully you won’t have any problems figuring it out without much commentary on the side from me.

Fire up a new instance of Visual Studio 2005 and in a new Windows Application project draw the following form:

Chat Server

The only controls we are interested in are the two TextBoxes (txtIp and txtLog) and the btnListen button. The IP address inside txtIp is the one where you want your chat server to be listening for incoming connections. You should use your local IP address, which if you’re not in a network it could be 192.168.0.1, but it’s best that you check using the ipconfig /all command in the MS-DOS Command Prompt window. The multi-line TextBox will hold information about connected clients and the messages that they are exchanging.

In the code view, start with the following using statements:

using System.Threading;

using System.Net;

using System.Net.Sockets;

using System.IO;

Move inside the class and declare a delagate which we will need in order to update the txtLog TextBox from another thread :

private delegate void UpdateStatusCallback(string strMessage);

Double-click the Start Listening button and you should arrive to it Click event. Have the event handler look like this:

private void btnListen_Click(object sender, EventArgs e)

{

// Parse the server’s IP address out of the TextBox

IPAddress ipAddr = IPAddress.Parse(txtIp.Text);

// Create a new instance of the ChatServer object

ChatServer mainServer = new ChatServer(ipAddr);

// Hook the StatusChanged event handler to mainServer_StatusChanged

ChatServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged);

// Start listening for connections

mainServer.StartListening();

// Show that we started to listen for connections

txtLog.AppendText(“Monitoring for connections…\r\n”);

}

A couple of objects are being instantiated, including a ChatServer object. We will write the ChatServer class very soon, and you will see that it handles all the incoming connections. In turn, it will make use of another class that we will write, called Connection.
The next thing we do is to set up an event handler for the StatusChanged event, which is a custom event that we’re going to write very soon. It will inform us when a client has connected, a new message has been received, a client has disconnected, etc.
Finally the StartListening() method tells the ChatServer object to start listening for incoming connections.

Believe it or not, there are only a few more lines of code to go in this class. One of them is the event handler that we hooked earlier, and the other is the UpdateStatus() method that gets called when an update needs to be made to the form. It’s needed because we use Invoke() and the delegate we created earlier to make a cross-thread call (since the ChatServer will be working in a different thread):

public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)

{

// Call the method that updates the form

this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });

}

private void UpdateStatus(string strMessage)

{

// Updates the log with the message

txtLog.AppendText(strMessage + “\r\n”);

}

And we’re done. Done with the Form1 class, of course. You should now create another file (I called mine ChatServer.cs) and inside it make sure you have all these using statements:

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.Net.Sockets;

using System.IO;

using System.Threading;

using System.Collections;

We’ll need to use an event that notifies the form class when a new client has connected, disconnected, sent a message, etc. In order to create our own custom event, we need to first define its arguments. More exactly we want a string argument that tells us what type of event has occured (user has connected, user has disconnected, user x says y, etc..) If you’re not familiar with events and delegates you might want to read the Delegates and Events in C# tutorial from a week ago. Here is the class that gets and sets the event arguments:

// Holds the arguments for the StatusChanged event

public class StatusChangedEventArgs : EventArgs

{

// The argument we’re interested in is a message describing the event

private string EventMsg;

// Property for retrieving and setting the event message

public string EventMessage

{

get

{

return EventMsg;

}

set

{

EventMsg = value;

}

}

// Constructor for setting the event message

public StatusChangedEventArgs(string strEventMsg)

{

EventMsg = strEventMsg;

}

}

Moving on, outside this class we declare the actual delegate for the event handler:

// This delegate is needed to specify the parameters we’re passing with our event

public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);

And now before we actually get to fire this event, we define the ChatServer class, in all its glory. Remember this is the class that we used back in Form1.cs:

class ChatServer

{

// This hash table stores users and connections (browsable by user)

public static Hashtable htUsers = new Hashtable(30); // 30 users at one time limit

// This hash table stores connections and users (browsable by connection)

public static Hashtable htConnections = new Hashtable(30); // 30 users at one time limit

// Will store the IP address passed to it

private IPAddress ipAddress;

private TcpClient tcpClient;

// The event and its argument will notify the form when a user has connected, disconnected, send message, etc.

public static event StatusChangedEventHandler StatusChanged;

private static StatusChangedEventArgs e;

// The constructor sets the IP address to the one retrieved by the instantiating object

public ChatServer(IPAddress address)

{

ipAddress = address;

}

// The thread that will hold the connection listener

private Thread thrListener;

// The TCP object that listens for connections

private TcpListener tlsClient;

// Will tell the while loop to keep monitoring for connections

bool ServRunning = false;

// Add the user to the hash tables

public static void AddUser(TcpClient tcpUser, string strUsername)

{

// First add the username and associated connection to both hash tables

ChatServer.htUsers.Add(strUsername, tcpUser);

ChatServer.htConnections.Add(tcpUser, strUsername);

// Tell of the new connection to all other users and to the server form

SendAdminMessage(htConnections[tcpUser] + ” has joined us”);

}

// Remove the user from the hash tables

public static void RemoveUser(TcpClient tcpUser)

{

// If the user is there

if (htConnections[tcpUser] != null)

{

// First show the information and tell the other users about the disconnection

SendAdminMessage(htConnections[tcpUser] + ” has left us”);

// Remove the user from the hash table

ChatServer.htUsers.Remove(ChatServer.htConnections[tcpUser]);

ChatServer.htConnections.Remove(tcpUser);

}

}

// This is called when we want to raise the StatusChanged event

public static void OnStatusChanged(StatusChangedEventArgs e)

{

StatusChangedEventHandler statusHandler = StatusChanged;

if (statusHandler != null)

{

// Invoke the delegate

statusHandler(null, e);

}

}

// Send administrative messages

public static void SendAdminMessage(string Message)

{

StreamWriter swSenderSender;

// First of all, show in our application who says what

e = new StatusChangedEventArgs(“Administrator: ” + Message);

OnStatusChanged(e);

// Create an array of TCP clients, the size of the number of users we have

TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];

// Copy the TcpClient objects into the array

ChatServer.htUsers.Values.CopyTo(tcpClients, 0);

// Loop through the list of TCP clients

for (int i = 0; i < tcpClients.Length; i++)

{

// Try sending a message to each

try

{

// If the message is blank or the connection is null, break out

if (Message.Trim() == “” || tcpClients[i] == null)

{

continue;

}

// Send the message to the current user in the loop

swSenderSender = new StreamWriter(tcpClients[i].GetStream());

swSenderSender.WriteLine(“Administrator: ” + Message);

swSenderSender.Flush();

swSenderSender = null;

}

catch // If there was a problem, the user is not there anymore, remove him

{

RemoveUser(tcpClients[i]);

}

}

}

// Send messages from one user to all the others

public static void SendMessage(string From, string Message)

{

StreamWriter swSenderSender;

// First of all, show in our application who says what

e = new StatusChangedEventArgs(From + ” says: ” + Message);

OnStatusChanged(e);

// Create an array of TCP clients, the size of the number of users we have

TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];

// Copy the TcpClient objects into the array

ChatServer.htUsers.Values.CopyTo(tcpClients, 0);

// Loop through the list of TCP clients

for (int i = 0; i < tcpClients.Length; i++)

{

// Try sending a message to each

try

{

// If the message is blank or the connection is null, break out

if (Message.Trim() == “” || tcpClients[i] == null)

{

continue;

}

// Send the message to the current user in the loop

swSenderSender = new StreamWriter(tcpClients[i].GetStream());

swSenderSender.WriteLine(From + ” says: ” + Message);

swSenderSender.Flush();

swSenderSender = null;

}

catch // If there was a problem, the user is not there anymore, remove him

{

RemoveUser(tcpClients[i]);

}

}

}

public void StartListening()

{

// Get the IP of the first network device, however this can prove unreliable on certain configurations

IPAddress ipaLocal = ipAddress;

// Create the TCP listener object using the IP of the server and the specified port

tlsClient = new TcpListener(1986);

// Start the TCP listener and listen for connections

tlsClient.Start();

// The while loop will check for true in this before checking for connections

ServRunning = true;

// Start the new tread that hosts the listener

thrListener = new Thread(KeepListening);

thrListener.Start();

}

private void KeepListening()

{

// While the server is running

while (ServRunning == true)

{

// Accept a pending connection

tcpClient = tlsClient.AcceptTcpClient();

// Create a new instance of Connection

Connection newConnection = new Connection(tcpClient);

}

}

}

Overwhelmed? It’s really not that complicated if you take it line by line and read the comments. It starts by defining two hash tables. These two hash tables will hold the username and the TCP connection associated with it. We need two of them because at one point we’ll want to retrieve the TCP connection by giving the username, and at some other point we’ll want to retrieve the username by giving the TCP connection. The 30 defines how many users the chat server can hold at one given point, but you can easily go into hundreds if needed, without worrying about a performance decrease.

The AddUser() method is obvious – it adds a new user to the hash tables, and thus to our list of connected chat clients. The RemoveUser() method does the opposite. The OnStatusChanged will fire the StatusChanged event, which is right now handled inside Form1.cs. Thus, it’s our way of updating the form with the latest message from inside this ChatServer object.

The SendAdminMessage sends an administrative message to all connected clients. You can see how it loops through the hash table and attempts to send them the message. If the message didn’t get through, they probably disconnected and we then remove them. This is very similar to what the SendMessage() method does, only that this time it sends a message from a specific chat client to all the others.

The StartListening() method is the one we called inside Form1, and it’s the fire starter, the instigator. It defines the first needed objects and starts a new thread that keeps listening for connections, and that is the KeepListening() method. And that’s where our story continues, because if you look inside the KeepListening() method you will see we create a new object of type Connection. That’s because each user connected to our server will have its own instance of Connection. If there are 10 users currently connected, there will be 10 instances of the Connection object. So let’s look at the final class of our chat server:

// This class handels connections; there will be as many instances of it as there will be connected users

class Connection

{

TcpClient tcpClient;

// The thread that will send information to the client

private Thread thrSender;

private StreamReader srReceiver;

private StreamWriter swSender;

private string currUser;

private string strResponse;

// The constructor of the class takes in a TCP connection

public Connection(TcpClient tcpCon)

{

tcpClient = tcpCon;

// The thread that accepts the client and awaits messages

thrSender = new Thread(AcceptClient);

// The thread calls the AcceptClient() method

thrSender.Start();

}

private void CloseConnection()

{

// Close the currently open objects

tcpClient.Close();

srReceiver.Close();

swSender.Close();

}

// Occures when a new client is accepted

private void AcceptClient()

{

srReceiver = new System.IO.StreamReader(tcpClient.GetStream());

swSender = new System.IO.StreamWriter(tcpClient.GetStream());

// Read the account information from the client

currUser = srReceiver.ReadLine();

// We got a response from the client

if (currUser != “”)

{

// Store the user name in the hash table

if (ChatServer.htUsers.Contains(currUser) == true)

{

// 0 means not connected

swSender.WriteLine(“0|This username already exists.”);

swSender.Flush();

CloseConnection();

return;

}

else if (currUser == “Administrator”)

{

// 0 means not connected

swSender.WriteLine(“0|This username is reserved.”);

swSender.Flush();

CloseConnection();

return;

}

else

{

// 1 means connected successfully

swSender.WriteLine(“1”);

swSender.Flush();

// Add the user to the hash tables and start listening for messages from him

ChatServer.AddUser(tcpClient, currUser);

}

}

else

{

CloseConnection();

return;

}

try

{

// Keep waiting for a message from the user

while ((strResponse = srReceiver.ReadLine()) != “”)

{

// If it’s invalid, remove the user

if (strResponse == null)

{

ChatServer.RemoveUser(tcpClient);

}

else

{

// Otherwise send the message to all the other users

ChatServer.SendMessage(currUser, strResponse);

}

}

}

catch

{

// If anything went wrong with this user, disconnect him

ChatServer.RemoveUser(tcpClient);

}

}

}

It doesn’t look too complicated, does it? There’s the constructor that initializes the TcpClient object, then there’s CloseConnection() which is called when we want to get rid of a currently connected client, and finally there’s AcceptClient() which checks for the username validity and if all is fine, it adds the user to the hash tables. If anything goes bad, it removes the user.

I’ll leave you chew on the code for a while now. It’s pretty much as easy as it can get for a C# based chat/server application, but that also means it can use more error handling. Also if you have any suggestions to improve the code or to fix a bug, feel free to post a comment below.

Chat Server Application

Converting RadEditor HTML to PDF format

The example below illustrates how you can convert the HTML of RadEditor to PDF format using an HTML2PDF convertor tool of Tall Components. For a live demo, please go to http://www.tallcomponents.com/cp0803.aspx

 

ASPX code

<form id=”Form1″ method=”post” runat=”server”>
    RadEditor id=”RadEditor1″ Runat=”server”>
    <asp:button id=”showPDF” runat=”server” Text=”Show PDF”></asp:button>

C# code

private void showPDF_Click(object sender, EventArgs e)
{
    string html = “<html>” + RadEditor1.Html + “</html>”;
    TallComponents.PDF.Layout.Document document = new TallComponents.PDF.Layout.Document();
    TallComponents.PDF.Layout.Section section = document.Sections.Add();
    TallComponents.PDF.Layout.HtmlParagraph htmlParagraph = new TallComponents.PDF.Layout.HtmlParagraph();
    htmlParagraph.FontPath = “fonts“;
    htmlParagraph.Text = html;
    section.Paragraphs.Add( htmlParagraph );
    Response.Clear();
    document.Write( Response );
    Response.End();
}

VB.NET code

Private Sub showPDF_Click(ByVal sender As Object, ByVal e As EventArgs)
 Dim html As String = “<html>” + RadEditor1.Html + “</html>”
 Dim document As TallComponents.PDF.Layout.Document = New TallComponents.PDF.Layout.Document
 Dim section As TallComponents.PDF.Layout.Section = document.Sections.Add
 Dim htmlParagraph As TallComponents.PDF.Layout.HtmlParagraph = New TallComponents.PDF.Layout.HtmlParagraph
 htmlParagraph.FontPath = “fonts”
 htmlParagraph.Text = html
 section.Paragraphs.Add(htmlParagraph)
 Response.Clear
 document.Write(Response)
 Response.End
End Sub

ASPX code

<form id=”Form1″ method=”post” runat=”server”>
    ScriptManager ID=”ScriptManager1″ runat=”server” />
    <telerik:RadEditor id=”RadEditor1″ Runat=”server”>
    <asp:button id=”showPDF” runat=”server” Text=”Show PDF”></asp:button>
</form>

C# code

private void showPDF_Click(object sender, EventArgs e)
{
    string html = “<html>” + RadEditor1.Content + “</html>”;
    TallComponents.PDF.Layout.Document document = new TallComponents.PDF.Layout.Document();
    TallComponents.PDF.Layout.Section section = document.Sections.Add();
    TallComponents.PDF.Layout.HtmlParagraph htmlParagraph = new TallComponents.PDF.Layout.HtmlParagraph();
    htmlParagraph.FontPath = “fonts”;
    htmlParagraph.Text = html;
    section.Paragraphs.Add( htmlParagraph );
    Response.Clear();
    document.Write( Response );
    Response.End();
}

VB.NET code

Private Sub showPDF_Click(ByVal sender As Object, ByVal e As EventArgs)
 Dim html As String = “<html>” + RadEditor1.Content+ “</html>”
 Dim document As TallComponents.PDF.Layout.Document = New TallComponents.PDF.Layout.Document
 Dim section As TallComponents.PDF.Layout.Section = document.Sections.Add
 Dim htmlParagraph As TallComponents.PDF.Layout.HtmlParagraph = New TallComponents.PDF.Layout.HtmlParagraph
 htmlParagraph.FontPath = “fonts”
 htmlParagraph.Text = html
 section.Paragraphs.Add(htmlParagraph)
 Response.Clear
 document.Write(Response)
 Response.End
End Sub

In the “Article Files” section, there is attached a sample project with RadEditor 6.1 demonstrating the described functionality.

Article Links

How do I pass JavaScript values to Scriptlet in JSP?

I can provide two ways,

a.jsp:

<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>

2)b.jsp:

<script>
var v="xyz";
</script>
<% String st="<script>document.writeln(v)</script>";
out.println("value="+st); %>

Web Services – Web Services Tutorials

In this section of the Web Services tutorial you will be familiarized with the Web Services.

Introduction

The next generation of distributed computing has arrived. A Web service is a unit of managed code that can be remotely invoked using HTTP, that is, it can be activated using HTTP requests.

Historically speaking, remote access to binary units required platform-specific and sometimes language-specific protocols. For example, DCOM clients access remote COM types using tightly coupled RPC calls. CORBA requires the use of tightly coupled protocol referred to as Internet Inter-ORB Protocol (IIOP), to activate remote types. Enterprise JavaBeans (EJBs) requires a Remote Method Invocation (RMI) Protocol and by and large a specific language (Java). Thus each of these remote invocation architectures needs proprietary protocols, which typically require a tight connection to the remote source.

One can access Web services using nothing but HTTP. Of all the protocols in existence today, HTTP is the one specific wire protocol that all platforms tend to agree on. Thus , using Web services, a Web service developer can use any language he wish and a Web service consumer can use standard HTTP to invoke methods a Web service provides. The bottom line is that we have true language and platform integration . Simple Object Access Protocol (SOAP) and XML are also two key pieces of the Web services architecture.

What is a Web Service

Web services constitute a distributed computer architecture made up of many different computers trying to communicate over the network to form one system. They consist of a set of standards that allow developers to implement distributed applications – using radically different tools provided by many different vendors – to create applications that use a combination of software modules called from systems in disparate departments or from other companies.

A Web service contains some number of classes, interfaces, enumerations and structures that provide black box functionality to remote clients. Web services typically define business objects that execute a unit of work (e.g., perform a calculation, read a data source, etc.) for the consumer and wait for the next request. Web service consumer does not necessarily need to be a browser-based client. Console-baed and Windows Forms-based clients can consume a Web service. In each case, the client indirectly interacts with the Web service through an intervening proxy. The proxy looks and feels like the real remote type and exposes the same set of methods. Under the hood, the proxy code really forwards the request to the Web service using standard HTTP or optionally SOAP messages.

Web Service Standards

Web services are registered and announced using the following services and protocols. Many of these and other standards are being worked out by the UDDI project, a group of industry leaders that is spearheading the early creation and design efforts.

Universal Description, Discovery, and Integration (UDDI) is a protocol for describing available Web services components. This standard allows businesses to register with an Internet directory that will help them advertise their services, so companies can find one another and conduct transactions over the Web. This registration and lookup task is done using XML and HTTP(S)-based mechanisms.

Simple Object Access Protocol (SOAP) is a protocol for initiating conversations with a UDDI Service. SOAP makes object access simple by allowing applications to invoke object methods or functions, residing on remote servers. A SOAP application creates a request block in XML, supplying the data needed by the remote method as well as the location of the remote object itself.

Web Service Description Language (WSDL), the proposed standard for how a Web service is described, is an XML-based service IDL (Interface Definitition Language) that defines the service interface and its implementation characteristics. WSDL is referenced by UDDI entries and describes the SOAP messages that define a particular Web service.

ebXML (e-business XML) defines core components, business processes, registry and repository, messaging services, trading partner agreements, and security.

Implementing Web Services

Here comes a brief step-by-step on how a Web service is implemented.

  • A service provider creates a Web service
  • The service provider uses WSDL to describe the service to a UDDI registry
  • The service provider registers the service in a UDDI registry and/or ebXML registry/repository.
  • Another service or consumer locates and requests the registered service by querying UDDI and/or ebXML registries.
  • The requesting service or user writes an application to bind the registered service using SOAP in the case of UDDI and/or ebXML
  • Data and messages are exchanged as XML over HTTP

Web Service Infrastructure

Even though Web services are being built using existing infrastructure, there exists a strong necessity for a number of innovative infrastructures. The core architectural foundation of Web services are XML, XML namespaces, and XML schema. UDDI, SOAP, WSDL, ebXML and security standards are being developed in parallel by different vendors

Web Services Technologies and Tools

There are a number of mechanisms for constructing Web services. Microsoft has come out with a new object-oriented language C# as the development language for Web services and .NET framework. Microsoft has an exciting tool called Visual Studio .NET in this regard. The back end database can be Microsoft SQL Server 2000 in Windows 2000 Professional.

Sun Microsystems has its own set of technologies and tools for facilitating Web services development. Java Servlets, Java Server Pages (JSPs), Enterprise JavaBeans (EJB) architecture and other Java 2 Enterprise Edition (J2EE) technologies play a very critical role in developing Web services.

There are a number of tools for developing Web services. They are Forte Java IDE, Oracle JDeveloper, and WebGain Studio.

Sun Microsystems has taken an initiative called Sun ONE (Open Network Environment) and is planning to push Java forward as a platform for Web services. It is developing Java APIs for XML-based remote procedure calls and for looking up services in XML registries – two more JAX family APIs: JAX/RPC (Java API for XML Remote Procedure Calls) and JAXR (Java API for XML Registries). These will wrap up implementations of Web services standards, such as SOAP and UDDI.

IBM also for its part has already developed a suite of early-access tools for Web services development. They are Web Services Toolkit (WSTK), WSDL Toolkit, and Web Services Development Environment (WSDE).

Apache Axis is an implementation of the SOAP (“Simple Object Access Protocol”) submission to W3C.

From the draft W3C specification:

SOAP is a lightweight protocol for exchanging structured information in a decentralized, distributed environment. It is an XML based protocol that consists of three parts: an envelope that defines a framework for describing what is in a message and how to process it, a set of encoding rules for expressing instances of application-defined datatypes, and a convention for representing remote procedure calls and responses.

Apache Axis is an Open Source SOAP server and client. SOAP is a mechanism for inter-application communication between systems written in arbitrary languages, across the Internet. SOAP usually exchanges messages over HTTP: the client POSTs a SOAP request, and receives either an HTTP success code and a SOAP response or an HTTP error code. Open Source means that you get the source, but that there is no formal support organization to help you when things go wrong.

Conclusion

For the last few years, XML has enabled heterogeneous computing environments to share information over the Web. It now offers a simplified means by which to share process as well. From a technical perspective, the advent of Web services is not a revolution in distributed computing. It is instead a natural evolution of XML application from structured representation of information to structured representation of inter-application messaging.

Prior to the advent of Web services, enterprise application integration (EAI) was very difficult due to differences in programming languages and middleware used within organizations. This led to the situation where interoperability was cumbersome and painful. With the arrival of Web services, any application can be integrated as long as it is Internet-enabled.

It is difficult to avoid the popularity and hype that is surrounding Web services. Each software vendor has some initiative concerning Web services and there is always great speculation about the future of the market for them. Whichever way it turns out, Web service architectures provide a very different way of thinking about software development. From client-server to n-tier systems, to distributed computing, Web service applications represent the culmination of each of these architectures in combination with the Internet.

Web Services with NetBeans IDE

Creating webservices in NetBeans.

In this example program I will show you how you can make webservices in the Netbeans IDE. NetBeans IDE provides necessary GUI Tool to help the developers to quickly develop and deploy web services.

In this example we will

a) Develop webservices

b) Test the webservice

c) Develop client and call the webservice there

d) Finally deploy and test the application

Web Service can be added in a Web project or in Ejb project. Netbeans IDE helps the developers to easily develop and test the webservices.
It’s easy to make the Web Service program in Netbeans, which has Glassfish server by default.

Web Service program in Web Project

In Netbeans take new web project in figure 1

Web Services Example

Figure 1

Give project name webservice1 as shown in figure 2

Web Services Example

Figure 2

Select the server name in figure 3

Web Services Example

Figure 3

Now Rt Click on the Web Service project in figure 4

Select New->WebService

Web Services Example

Figure 4

Now give the name of the Web Service and package name figure 5

Web Services Example

Figure 5

Now In design view of Web Service click on Add Operation in figure 6

Web Services Example

Figure 6

Here give the operation name and parameter name and type as shown in figure 7

Web Services Example

Figure 7

Now in source view change the return null to return “hello ”+name as in figure 8

Web Services Example

Figure 8

Now Rt Click on the project and deploy it on the server as in figure 9

Web Services Example

Figure 9

It will deploy the war file on to the server

Now test the web service program

Rt click on the MyWebService in web services folder and select Test Web Operation as in figure 10

Web Services Example

Figure 10

It will open the Web Service program in browser as in figure 11

Web Services Example

Figure 11

Click on WSDL File in blue color .It will open the WSDL file in the browser as in figure 12

Web Services Example

Figure 12

Now as in fig type the roseindia in the text field and click on show button as in figure 13

Web Services Example

Figure 13

It will return hello roseindia

It also give the SOAP request and SOAP response pf the Web Service as in figure 14

Web Services Example

Figure 14

Now make the client file.Client file can be java servlet , jsp and standalone java file

Start a new web project as in figure 15.

Give project name as Webservice1-client

Web Services Example

Now Rt. Click on the project select NewàWeb Service client

Here now select the WSDL file of the Web Service as in figure 15

Click on the Browse.

Web Services Example

Now select the webservice1àMyWebService

Web Services Example

Figure 15

It creates the Client environments for the Web Service in the given project

Now make a Client file by just taking a new Jsp file as in figure 16

Web Services Example

Figure 16

Give the file name as client.jsp

Rt click in client.jsp file code and select Web Service Client resources –>Call Web Service Operation in figure 17

Web Services Example

Figure 17

Select the web service project ->web service file->web service port->operation name as in figure 18

Web Services Example

Figure 18

Change the name =”null” to name=”roseindia” as in figure 19

Web Services Example

Figure 19

Rt click in client.jsp and select run client.jsp

Web Services Example

Download Code

Java Building a Simple Web Service ? A Tutorial Tutorial

·

Introduction

 

In
this tutorial we will create a simple web service and a client web application
using eclipse IDE along with
Lomboz
plug
in.
We
will also deploy and test the web service on Tomcat 5.5.4 web application
server. This application, while simple, provides a good introduction to Web
service development and some of the Web development tools available.

 

·
Environment

 

J2SDK
1.4.2

http://java.sun.com/

 

Eclipse
3.1

 

http://www.eclipse.org/

 

 

Tomcat
5.5.4

 

http://tomcat.apache.org/

 

 

Lomboz
3.1RC2

http://lomboz.objectweb.org/

 

 

 

·
Installation

 

Install
JDK (in D:\j2sdk1.4.2_04)

 

Install
Tomcat (in E:\Tomcat5.5)

 

Install
Eclipse (in E:\Eclipse3.1)

 

Install
Lomboz (in E:\Eclipse3.1)

 

·
Setting up

 

  1. Set
    up the installed JRE in eclipse (Windows -> Preferences -> Java ->
    Installed JREs)
     

 

 

  1. Set
    up the installed runtime for server in eclipse (Windows -> Preferences
    -> Server -> Installed Runtimes)
     

 

 

  1. Set
    up the Server view in eclipse (Windows -> Show View -> Other)
     

 


 

 

  1. Set
    up the Tomcat Server by right clicking and selecting New -> Server option
    from the Server view in eclipse
     

 

 

 

 

 

 

·
Creating a Web service

 

  1. Create
    a new Dynamic Web Project in eclipse (File -> New -> Other)
     

 

 

 

  1. Enter
    name as ?WebServiceTutorial?, select project location as ?E:\Test?
    and select Apache Tomcat v5.5 as the Target server.
     

 

 

 

  1. Now
    create a new Java class from the Project Explorer (Dynamic Web Projects
    -> Java Source -> New -> Class)
     

 

 

 

  1. Enter
    name as ?Hello? and package as ?com.tutorial?.
     

 

 

  1. Add
    a simple method in the ?Hello? class as below.
     


public String sayHello(String name){

 


return “Hello ” + name;

 


}

 


 

 

  1. Save
    and build the project.
     
  2. Create
    a new Web service in eclipse (File -> New -> Other)
     

 

 

  1. Select
    Generate a proxy.
     
  2. Select
    Test the Web service.
     
  3. Select
    Overwrite files without warning.
     

 

 

  1. Select
    or enter the Bean name as ?com.tutorial.Hello?. This is the java class
    that we just now created.
     

 

 

  1. Continue
    the wizard by clicking Next and finish.
     
  2. On
    Finish, the Tomcat server starts up and launches the Test client.
     
  3. Verify
    the generated contents. Look for Hello.class and the generated JSPs as
    below.
     

 

 

 

 

 

  1. Verify
    the Tomcat folder and ensure the newly created web applications ?
    WebServiceTutorial, WebServiceTutorialClient.
     

 

 

 

 

  1. We
    can also run the following url from the browser to access/test the Web
    service.
     

http://localhost:8080/WebServiceTutorialClient/sampleHelloProxy/TestClient.jsp

 

 

  1. If
    servlet error ?org.eclipse.jst.ws.util.JspUtils cannot be resolved or is
    not a type? is thrown on the browser, then copy the webserviceutils.jar
    file from the E:\Eclipse3.1\eclipse\plugins\org.eclipse.jst.ws.consumption_0.7.0
    into the WEB-INF\lib folder of the WebServiceTutorialClient application and
    restart the Tomcat server.
     
  1. The
    browser displays the methods available in the web service.
     

 

 

 

  1. Click
    on the sayHello(..) method, enter your name (for e.g. ?Jeeva?) in
    the inputs section and click ?Invoke?.
     

 

 

 

  1. The
    browser greets using the web service.
     

 

 

 

 

 

  1. The
    WSDL for the Hello Web service can be found in E:\Test\WebServiceTutorial\WebContent\wsdl\Hello.wsdl.
    On double-click, the WSDL opens in a graphical editor.
     

 

 

 

  1. Right-click
    on the WSDL file and explore the options to test the web service / publish
    the WSDL file / generate client / etc.
     

 

 

 

 

·
Conclusion

 

In this
tutorial we learned how to create a simple web service and a client web
application using eclipse IDE along with
Lomboz
plug
in.
We
also deployed and tested the web service on Tomcat 5.5.4 web application server.
This application, while simple, provides a good introduction to Web service
development and some of the Web development tools available.

Reference # http://www.roseindia.net/webservices/buildingsimplewebservice.shtml