Пример веб-службы с применением WCF: клиент
1) создать ссылку на сервис (servicereference): выбрать пункт «Добавить ссылку на службу…» контекстного меню обозревателя решений VisualStudio;
2) задать адрес WSDLсхемы. После нажатия «Перейти» произойдет загрузка и служба WeatherService, у которой есть интерфейс с двумя методами (GetTemperatureи GetWeatherInfo)будет найдена;
3) при нажатии кнопки «ОК» по схеме службы будет сгенерирован программный код клиента. Сама ссылка появляется в папке “Servicereferences”;
4) Для обновления ссылки на сервис (перечитать WSDL-сервиса и заново сгенерировать программный код клиента) необходимо выбрать пункт «Обновить ссылку на сервис» в контекстном меню созданной ссылки.
СгенерированныйклассWeatherServiceClient:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
publicpartialclassWeatherServiceClient : System.ServiceModel.ClientBase<WcfServiceClient.ServiceReference1.WeatherService>, WcfServiceClient.ServiceReference1.WeatherService {
public WeatherServiceClient() {
}
public WeatherServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public WeatherServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public WeatherServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public WeatherServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
publicdouble GetTemperature(string location) {
returnbase.Channel.GetTemperature(location);
}
public WcfServiceClient.ServiceReference1.WeatherInfo GetWeatherInfo(string location)
{
returnbase.Channel.GetWeatherInfo(location);
|
|
}
}
WeatherServiceClient – прокси на стороне клиента. Этот класс реализует интерфейс для работы с созданной веб-службой.
staticvoid Main(string[] args)
{
var client = newWeatherServiceClient(
newWSHttpBinding(SecurityMode.None, false),
newEndpointAddress("net.tcp://localhost:5555/Design_Time_Addresses/WcfServiceLibrary1/WeatherService/"));
var t = client.GetTemprature("Minsk");
var w = client.GetWeatherInfo("Minsk");
Console.WriteLine("Temperature: {0}, Humidity: {1}, Pressure: {2}",
w.Temperature, w.Humidity, w.Pressure);
var sw = Stopwatch.StartNew();
var count = 1000;
for (int i = 0; i < count; i++)
var wh = client.GetWeatherInfo("Minsk");
Console.WriteLine("{0} calls of GetTemprature(\"Minsk\") took {1}", count, sw.Elapsed);
Console.WriteLine("1 call of GetTemprature(\"Minsk\") takes {0} ms", (double)sw.ElapsedMilliseconds / count);
client.Close();
client = newWeatherServiceClient(
newWSHttpBinding(SecurityMode.Message),
newEndpointAddress("http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/WeatherService/"));
t = client.GetTemprature("Minsk");
w = client.GetWeatherInfo("Minsk");
Console.WriteLine("Temperature: {0}, Humidity: {1}, Pressure: {2}",
w.Temperature, w.Humidity, w.Pressure);
sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
var wh = client.GetWeatherInfo("Minsk");
Console.WriteLine("{0} calls of GetTemprature(\"Minsk\") took {1}", count, sw.Elapsed);
Console.WriteLine("1 call of GetTemprature(\"Minsk\") takes {0} ms", (double)sw.ElapsedMilliseconds / count);
client.Close();
Console.ReadLine();
}
Представленная выше программа служит для проверки производительности: в зависимости от конфигурации компьютера при расположении службы и клиента на одной машине она показывает, что 1000 вызовов GetTemperatureзанимает около 7-8 секунд, то есть один вызов метода занимает 0,007-0,008 секунды или 7-8 миллисекунд.
|
|
Результат работы программы показывает, что удаленные вызовы заметно замедляют выполнение. Поэтому очень важно грамотное проектирование распределенных программ и обдуманное использование удаленных вызовов.
Дата добавления: 2018-08-06; просмотров: 264; Мы поможем в написании вашей работы! |
Мы поможем в написании ваших работ!