
Получение wsdl сервиса
Теперь можно запустить консольное приложение-хост (в противном случае, конечные точки будут недоступны) и перейти к URI службы http://localhost:8080/
Вы увидите экран со ссылкой на WSDL сервиса http://localhost:8080/?wsdl.
Приложение-клиент
Необходимо создать прокси-класс, который будет находиться между нашим клиентом и службой. Один из способов создания прокси-класса – воспользоваться генератором прокси svcutil.exe. Для этого необходимо ввести в командной строке VisualStudioследующую команду, находясь в папке расположения «Client»:
> svcutil http://localhost:8080/ /o:ServiceProxy.cs /config:App.Config /n:*,Client
Эта команда сгенерирует два файла: прокси службы и файл конфигурации приложения, которые необходимо включить в проект.
Когда мы запустили svcutil.exe мы передали ему в качестве первого аргумента место расположения нашей службы, как указано в хосте. Это и есть базовый адрес. Вторым аргументом является прокси. Третий аргумент указывает, что мы также хотим обновить конфигурацию приложения, а если она не доступна, создать её. Последний аргумент – пространство имён для прокси.
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<wsDualHttpBinding>
<binding name="WSDualHttpBinding_IStringCrypt" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192"
maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" />
<security mode="Message">
<message clientCredentialType="Windows"
negotiateServiceCredential="true"
algorithmSuite="Default" />
</security>
</binding>
</wsDualHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8080/" binding="wsDualHttpBinding"
bindingConfiguration="WSDualHttpBinding_IStringCrypt"
contract="Client.IStringCrypt"
name="WSDualHttpBinding_IStringCrypt"/>
</client>
</system.serviceModel>
</configuration>
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
namespace Client
{
public partial class ClientForm : Form
{
const int MD5 = 0;
const int SHA1 = 1;
const int SHA256 = 2;
const int SHA512 = 3;
StringCryptClient client;
public class CallbackHandler : IStringCryptCallback
{
ClientForm form;
public CallbackHandler(ClientForm form) {
this.form = form;
}
public void count(int count) {
form.infoLabel.Text = "Общее число клиентов " + count;
}
}
public ClientForm() {
InitializeComponent();
algComboBox.SelectedIndex = MD5;
try {
InstanceContext instanceContext = new InstanceContext(new CallbackHandler(this));
client = new StringCryptClient(instanceContext);
client.join();
}
catch (Exception e) {
MessageBox.Show(e.Message); return;
}
}
private void hashRefresh()
{
const string defaultText = "";
string str = strTextBox.Text;
if (string.IsNullOrEmpty(str)) {
hashTextBox.Text = defaultText; return;
}
string hash;
try {
switch (algComboBox.SelectedIndex) {
case MD5: hash = client.md5(str); break;
case SHA1: hash = client.sha1(str); break;
case SHA256: hash = client.sha256(str); break;
case SHA512: hash = client.sha512(str); break;
default: hashTextBox.Text = defaultText; return;
}
}
catch (Exception e) {
MessageBox.Show(e.Message);
hashTextBox.Text = defaultText;
return;
}
hashTextBox.Text = hash;
}
private void strTextBox_TextChanged(object sender, EventArgs e) {
hashRefresh();
}
private void algComboBox_SelectedIndexChanged(object sender, EventArgs e) {
hashRefresh();
}
private void ClientForm_FormClosed(object sender, FormClosedEventArgs e) {
client.leave();
client.Close();
}
}
}