Hi _unmanaged,
From my experience, the issue is mostly not related to the project type, such as Console project or WinForm project. I have tested your code snippet in a WinForm project but did not meet the issue you mentioned. Instead, when I clicked the button twice, I met this error:
The ChannelDispatcher at 'net.tcp://localhost:6669/MessageService' with contract(s) '"ISimpleContract"' is unable to open its IChannelListener.
This is because that the server open a new service when I clicked the button again and this service uses the same port(6669). This leads to a port conflict.
Could you please let me know where the exception was thrown and its detail information? It is appreciated if you could provide more information about your test environment and steps.
I suggest that we put the code snippet which starts the service in the Load event handler of the Form, this would avoid service be started twice. This is a code snippet:
private void button1_Click(object sender, EventArgs e)
{
Thread client = new Thread(new ThreadStart(ClientProc));
client.Start();
Console.WriteLine("Service was succesfully hosted. Press [enter] to exit...");
Console.ReadLine();
}
void ClientProc()
{
Thread.Sleep(2000);
var channelFactory = new ChannelFactory<ISimpleContract>(new NetTcpBinding());
var service = channelFactory.CreateChannel(new EndpointAddress(@"net.tcp://localhost:6669/MessageService"));
string s = service.GetCurrentTime();
}
private void Form1_Load(object sender, EventArgs e)
{
var serviceHost = new ServiceHost(new SimpleService());
serviceHost.AddServiceEndpoint(typeof(ISimpleContract), new NetTcpBinding(), @"net.tcp://localhost:6669/MessageService");
serviceHost.Open();
}
I also suggest dividing the project into three projects: one server, one client and the other contract. This would make the architecture clearer.
This is a sample about how to use WCF service on WinForm:
http://www.codeproject.com/KB/WCF/wcffileserver.aspx.
You can get more information about WCF from:
http://msdn.microsoft.com/en-us/library/ms735119.aspx.
Let me know if this helps.
Aland Li
Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.