WCF 服务器与客户端同在一个项目问题
本帖最后由 eugeneyj 于 2013-04-27 10:45:00 编辑 我想在一个项目中即是客户端又是服务器,放在一个窗体里面就会报错,当打开两个exe文件,一个开服务端,一个当客户端就可以正常连接!
以下代码,刚接触WCF 求讲解
WCF 协议 tcp
/// <summary>
/// 链接服务器 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
string address = "net.tcp://localhost:6666/hello";
ChannelFactory<WindowsServer.Client.IHello> myChannelFactory = new ChannelFactory<WindowsServer.Client.IHello>(new NetTcpBinding(SecurityMode.None), new EndpointAddress(address));
WindowsServer.Client.IHello wcfClient = myChannelFactory.CreateChannel();
using (wcfClient as IDisposable)
{
wcfClient.Say(messText.Text);
}
}
public ServiceHost StartTCPServer()
{
try
{
Uri baseAddress = new Uri("http://localhost:8889");
string address = "net.tcp://localhost:6666/hello";
ServiceHost serviceHost = new ServiceHost(typeof(HelloService), baseAddress);
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
serviceHost.AddServiceEndpoint(typeof(WindowsServer.Services.IHello), binding, address);
serviceHost.Open();
return serviceHost;
}
catch (Exception ex)
{
}
return null;
}
ServiceHost ServiceHostParam=null ;
/// <summary>
/// 启动服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
ServiceHostParam= StartTCPServer();
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
ServiceHostParam.Close();
}
/////////////////客户端IHello//////////////////////
namespace WindowsServer.Client
{
[ServiceContract]
interface IHello
{
[OperationContract(IsOneWay = true)]
void Say(string name);
[OperationContract(IsOneWay = true)]
void Say1(string name);
}
}
////////////////////服务端IHello/////////////////////////////
[ServiceContract]
public interface IHello
{
[OperationContract(IsOneWay =true )]
void Say(string name);
[OperationContract(IsOneWay = true)]
void Say1(string name);
}
////////////////////////服务端IHello接口实现类//////////////////////////////////////
[ServiceBehavior]
public class HelloService:IHello
{
[OperationBehavior]
public void Say(string name)
{
OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpointProperty =messageProperties[RemoteEndpointMessageProperty.Name]
as RemoteEndpointMessageProperty;
Console.WriteLine( string.Format("Hello {0}! Your IP address is {1} and your port is {2}", name, endpointProperty.Address, endpointProperty.Port));
}
[OperationBehavior]
public void Say1(string name)
{
}
}
[解决办法]
我的理解,大概原因是你的客户端和服务器端都监控了同一个端口。当是一个应用程序时,就分不清你的请求和回复是源自客户端还是服务器端了。