我的申请基于this tutorial
我用来测试与服务器的连接的方法(在客户端应用程序中):
public class PBMBService : IService
{
private void btnPing_Click(object sender, EventArgs e)
{
ServiceClient service = new ServiceClient();
tbInfo.Text = service.Ping().Replace("\n", "\r\n");
service.Close();
}
//other methods
}
服务主要功能:
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/PBMB");
ServiceHost selfHost = new ServiceHost(typeof(PBMBService), baseAddress);
try
{
selfHost.AddServiceEndpoint(
typeof(IService),
new WSHttpBinding(),
"PBMBService");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
selfHost.Open();
Console.WriteLine("Serwis gotowy.");
Console.WriteLine("Naciśnij <ENTER> aby zamknąć serwis.");
Console.WriteLine();
Console.ReadLine();
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("Nastąpił wyjątek: {0}", ce.Message);
selfHost.Abort();
}
}
}
Ping()函数decaration
[ServiceContract(Namespace = "http://PBMB")]
public interface IService
{
[OperationContract]
string Ping();
}
Ping()函数实现
public class PBMBService : IService
{
SqlConnection sql = new SqlConnection(@"Data Source=.\SqlExpress;Initial Catalog=PBMB;Integrated Security=True");
SqlCommand cmd;
private void Message(string message)
{
Console.WriteLine(DateTime.Now + " -> " + message);
}
public string Ping()
{
Message("Ping()");
return "Metoda Ping() działa.";
}
}
如何在Message方法中放置来电者的IP?
答案 0 :(得分:1)
原始博客可通过Wayback Machine获取。请注意,您需要根据作者的帖子使用WCF 3.5或更高版本。
文章的代码如下;
服务合同
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace ClientInfoSample
{
[ServiceContract]
public interface IService
{
[OperationContract]
string GetData(string value);
}
}
检索IP的实施:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Channels;
namespace ClientInfoSample
{
public class MyService : IService
{
public string GetData(string value)
{
OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
return string.Format("Hello {0}! Your IP address is {1} and your port is {2}", value, endpointProperty.Address, endpointProperty.Port);
}
}
}
答案 1 :(得分:0)
你在寻找像
这样的东西吗?HttpContext.Current.Request.UserHostAddress