开发者

Calling a Java Web service from silverlight throws an exception

开发者 https://www.devze.com 2023-02-23 09:27 出处:网络
After my previous question HERE, I found the solution (well, part of it). Here\'s the code for Java part:

After my previous question HERE, I found the solution (well, part of it).

Here's the code for Java part:

@WebService

public class MyWebService {

@WebMethod public String myMethod() {

return "Hello World"; }

@WebMethod
public int Add(@WebParam(name="a") int a,
               @WebParam(name="b") int b)
{
    return a + b;
}


public static void main(String[] args) 
{       
    String address = "http://127.0.0.1:8023/_WebServiceDemo";
    Endpoint.publish(address, new MyWebService());
    System.out.println("Listening: " + address);
}

}

And Here is the Silverlight part:

private void SearchResultList_SelectionChanged(object sender, SelectionChanged开发者_开发百科EventArgs e)
    {
        MyWebServiceClient proxy = new MyWebServiceClient();
        proxy.AddCompleted += proxy_AddCompleted;
        proxy.AddAsync(2, 3);
    }

    void proxy_AddCompleted(object sender, AddCompletedEventArgs e)
    {
        txtSearch.Text = e.Result.ToString();
    }

But when I run this, e.Result throws an exception. What am I missing/ How should I solve it?

Note that this code runs perfectly in C# Console application (when it's not async). But when I run the async code, it doesn't work.

Thanks in advance.


I guess you are getting a System.ServiceModel.CommunicationException when trying to access the Java Webservice from Silverlight.

There is nothing basically wrong with your code, and it should also work with async calls in C# Console App.

The main problem is that Silverlight (as a browser plugin) enforces some security restrictions that prevent a Silverlight Application to talk to another server than the one loaded from (defined by server name and port) without further configuration. This behaviour can be configured as described here (also search for "silverlight cross-domain calls" or "silverlight cross domain policy").

This restrictions (normally) do not apply to desktop or console applications so they'll work fine with the same web service.

To make your code work you need to host the Silverlight Application inside the same "project" / website than your webservice (so I suppose, the self-hosting webservice won't work and you need to switch to Java web project where the webservice is to be hosted). As the Silverlight Application basically consists of an enclosing HTML file plus the referenced binaries, you can host it on any server, e.g. Apache Tomcat.

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消