SignalR on localhost [duplicate] - c#

This question already exists:
SignalR Server Hosting Localhost
Closed 5 years ago.
I'm running a server with a localhost http://*:52080.
On the same computer, I'm run client and trying to connect to a local IP hub http://192.168.1.102:52080/signalr. Everything works well.
But if I run the client on another computer (from the same local network) and try to connect to http://192.168.1.102:52080/signalr, it does not connect. The client catches an exception ("System.AggregateException" in mscorlib.dll).
Port 52080 on the computer with the hub is open.
What could be the reason for the failure?
Server:
using System;
using Microsoft.Owin.Hosting;
public class Program
{
static void Main(string[] args)
{
string url = "http://*:52080";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine("Server running at {0}\n", url);
Console.ReadLine();
}
}
}
Startup.cs
using Owin;
using Microsoft.Owin.Cors;
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
SGHub.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using System.Collections.Generic;
public class SGHub : Hub
{
public static List<string> Users = new List<string>();
public override Task OnConnected()
{
Console.WriteLine("\nOnConnected {0}", Context.ConnectionId);
Users.Add(Context.ConnectionId);
Clients.Caller.broadcastMessage("Server:", "Successful connection");
Clients.Others.broadcastMessage("Server:", "New connection");
return (base.OnConnected());
}
}
Client:
using System;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Hubs;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string serverURL = "http://192.168.1.102:52080/signalr";
Console.WriteLine("Connection to {0}\n", serverURL);
HubConnection hubConnection = new HubConnection(serverURL);
IHubProxy myHubProxy = hubConnection.CreateHubProxy("StartGameHub");
myHubProxy.On<string, string>("Send", (name, message) => Console.Write("Recieved addMessage: " + name + ": " + message + "\n"));
myHubProxy.On("heartbeat", () => Console.Write("Recieved heartbeat \n"));
Subscription subscription = myHubProxy.Subscribe("broadcastMessage");
subscription.Received += SubscriptionData;
while (true)
{
string key = Console.ReadLine();
if (key.ToUpper() == "A")
{
try
{
Console.WriteLine("Start connect..");
hubConnection.Start().Wait();
}
catch (System.AggregateException e)
{
Console.WriteLine("Connected fauld :(");
}
}
}
}
private static void SubscriptionData(IList<JToken> obj)
{
Console.WriteLine(obj[1].ToString());
}
}

The problem wasn`t in the code and the implementation method, but in the banal glitch of the router, after it rebooted and rebooted all computers (just in case) everything worked.

Related

HttpListener won't work over network even with firewall allowed

I'm using the following code to add a http listener:
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, HttpListenerResponse, string> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, HttpListenerResponse, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required, for example
// "http://localhost:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// A responder method is required
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
_listener.Prefixes.Add(s);
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, HttpListenerResponse, string> method, params string[] prefixes)
: this(prefixes, method) { }
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
//Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request, ctx.Response);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch { } // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } // suppress any exceptions
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
static class Program
{
public const int PORT = 18991;
[STAThread]
static void Main()
{
WebServer ws = new WebServer(SendResponse, "http://+:" + PORT + "/");
ws.Run();
Application.Run(new Form1());
ws?.Stop();
}
private static string SendResponse(HttpListenerRequest request, HttpListenerResponse response)
{
return "ok";
}
}
This works fine on the local machine, however it won't listen to request from other devices inside the network. I even added a outgoing incoming rule to the firewall allowing the connection, I added the URL using netsh http add urlacl url="http://+:18991/" user=everyone and started the application with admin rights, but no success.
How can I allow requests from remote devices inside the LAN?
Here are steps that you can try and see if they help:
Start Visual Studio as administrator:
Start your application in debug mode.
Open Resource Monitor in Windows and ensure that the port is present and set to Allowed, not restricted:
If not, add an inbound firewall rule for the port:
Allow it on all domains:
Allow programs:
Allow the connection:
Start HttpListener in the following way:
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace HttpTestServer
{
public class MainWindow
{
private readonly HttpListener _httpListener;
public MainWindow()
{
_httpListener = new HttpListener();
_httpListener.Prefixes.Add("http://*:9191/");
Task.Run(Start);
}
public async Task Start()
{
_httpListener.Start();
while (true)
{
var context = await _httpListener.GetContextAsync();
using (var sw = new StreamWriter(context.Response.OutputStream))
{
await sw.FlushAsync();
}
}
}
}
}
Run ipconfig and check what IP address you have:
Ping your computer from the other computer on the network:
From the other computer, also test to send an HTTP request to your computer:

How to use TCP client/listener in multithreaded c#?

I have written this code for my server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
private static bool terminate;
public static bool Terminate
{
get { return terminate; }
}
private static int clientNumber = 0;
private static TcpListener tcpListener;
static void Main(string[] args)
{
StartServer();
Console.Read();
}
private static void StartServer()
{
try
{
Console.WriteLine("Server starting...");
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8000);
terminate = false;
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(ConnectionHandler, null);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Server stopping...");
terminate = true;
if (tcpListener != null)
{
tcpListener.Stop();
}
}
}
private static void ConnectionHandler(IAsyncResult result)
{
TcpClient client = null;
try
{
client = tcpListener.EndAcceptTcpClient(result);
}
catch (Exception)
{
return;
}
tcpListener.BeginAcceptTcpClient(ConnectionHandler, null);
if (client!=null)
{
Interlocked.Increment(ref clientNumber);
string clientName = clientNumber.ToString();
new ClientHandler(client, clientName);
}
}
}
}
class ClientHandler
{
private TcpClient client;
private string ID;
internal ClientHandler(TcpClient client, string ID)
{
this.client = client;
this.ID = ID;
Thread thread = new Thread(ProcessConnection);
thread.IsBackground = true;
thread.Start();
}
private void ProcessConnection()
{
using (client)
{
using (BinaryReader reader=new BinaryReader(client.GetStream()))
{
if (reader.ReadString()==Responses.RequestConnect)
{
using (BinaryWriter writer=new BinaryWriter(client.GetStream()))
{
writer.Write(Responses.AcknowledgeOK);
Console.WriteLine("Client: "+ID);
string message = string.Empty;
while (message!=Responses.Disconnect)
{
try
{
message = reader.ReadString();
}
catch
{
continue;
}
if (message==Responses.RequestData)
{
writer.Write("Data Command Received");
}
else if (message==Responses.Disconnect)
{
Console.WriteLine("Client disconnected: "+ID);
}
else
{
Console.WriteLine("Unknown Command");
}
}
}
}
else
{
Console.WriteLine("Unable to connect client: "+ID);
}
}
}
}
}
class Responses
{
public const string AcknowledgeOK = "OK";
public const string AcknowledgeCancel = "Cancel";
public const string Disconnect = "Bye";
public const string RequestConnect = "Hello";
public const string RequestData = "Data";
}
this code listen for client requests in a multi threaded way. I am unable to understand how can i distinguish between different clients connected to my this server and which client is disconnecting and requesting for different commands.
my client code is:
private static void clietnRequest(string message,ref string response)
{
using (TcpClient client = new TcpClient())
{
if (!client.Connected)
{
client.Connect(IPAddress.Parse("127.0.0.1"), 8000);
using (NetworkStream networkStream = client.GetStream())
{
using (BinaryWriter writer = new BinaryWriter(networkStream))
{
writer.Write(Responses.RequestConnect);
using (BinaryReader reader = new BinaryReader(networkStream))
{
if (reader.ReadString() == Responses.AcknowledgeOK)
{
response = Responses.AcknowledgeOK;
}
}
}
}
}
}
}
this piece of code connects the client to server, but i am unable to send anymore messages. I want in my app if client is connected then he can send commands to server. instead of doing this it every time act as a new client to server. I am missing some thing here, Kindly guide me in right direction. I am totally new to c# networking programming. Kindly help me improve my code. Tcp Listener and Tcp Client is valid for this scenario or do I need to use Sockets?
You are closing the connection every time client side after you send a message, if you want to do that there is nothing wrong with it but you will need to send some form of identification to the server so it can tell that this is not a new connection but a old connection connecting in for a second time. This is EXACTLY what the HTTP protocol is doing and that "identification" are internet cookies.
That first option is fine if you transmit data very infrequently but if you are doing it more often you need to keep the connection open.
Basicly you need to take the act of connecting and disconnecting out of the client request function and pass the open connection in as a argument.
private void MainCode()
{
using (TcpClient client = new TcpClient())
{
client.Connect(IPAddress.Parse("127.0.0.1"), 8000);
while(variableThatRepresentsRunning)
{
//(Snip logic that gererates the message)
clietnRequest(message, ref response, client);
//(Snip more logic)
}
}
}
private static void clietnRequest(string message,ref string response, TcpClient client)
{
if (client.Connected)
{
using (NetworkStream networkStream = client.GetStream())
{
using (BinaryWriter writer = new BinaryWriter(networkStream))
{
writer.Write(Responses.RequestConnect);
using (BinaryReader reader = new BinaryReader(networkStream))
{
if (reader.ReadString() == Responses.AcknowledgeOK)
{
response = Responses.AcknowledgeOK;
}
}
}
}
}
else
{
//Show some error because the client was not connected
}
}
By doing it this way the client object server side represents the client, you will have one instance of it per connected client and will remain associated with that client till he disconnects. If you want to track all of the connected clients you will need to insert them all in to some collection like a List<TcpClient> (either use a Concurrent Collection or use locking because you are multi-threaded) and then you will have a list of all clients (you will need to have the clients clean up after themselves so they remove themselves from the list after a disconnection).

SignalR: I cannot call .net client method from server

I would like to implement a pub/sub application with .NET clients, so I'm testing SignalR by means of this minimal code.
This is the server:
namespace Test.SignalRComm.SimpleServer
{
using System.Threading.Tasks;
using log4net;
using SignalR;
using SignalR.Hosting.Self;
using SignalR.Hubs;
using SignalR.Infrastructure;
class Program
{
private static SignalRServer signalRServer = null;
static void Main(string[] args)
{
signalRServer = new SignalRServer();
signalRServer.Start();
System.Console.WriteLine("Press Enter to close...");
System.Console.ReadLine();
signalRServer.Stop();
}
}
public class SignalRServer
{
private string serverUrl = null;
public Server signalRServer = null;
public SignalRServer()
{
serverUrl = #"http://localhost:5001/";
signalRServer = new SignalR.Hosting.Self.Server(serverUrl);
signalRServer.EnableHubs();
}
public void Start()
{
signalRServer.Start();
}
public void Stop()
{
IConnectionManager connManager = signalRServer.DependencyResolver.Resolve<IConnectionManager>();
dynamic clients = connManager.GetClients<SignalRTestHub>();
clients.AddMessage("Test");
signalRServer.Stop();
}
}
public class SignalRTestHub : Hub, IDisconnect
{
private static readonly ILog logger = LogManager.GetLogger(typeof(SignalRTestHub));
public void Register(string token)
{
AddToGroup(token).ContinueWith(task =>
{
if (task.IsFaulted)
logger.Error(task.Exception.GetBaseException());
else
{
string message = string.Format("Client {0} registered with token <{1}>", Context.ConnectionId, token);
logger.Info(message);
}
});
}
public void Unregister(string token)
{
RemoveFromGroup(token).ContinueWith(task =>
{
if (task.IsFaulted)
logger.Error(task.Exception.GetBaseException());
else
logger.InfoFormat("Client {0} unregistered from token <{1}>", Context.ConnectionId, token);
});
}
public Task Disconnect()
{
string message = string.Format("Client {0} disconnected", Context.ConnectionId);
logger.Info(message);
return null;
}
}
}
and this is the client:
namespace Test.SignalRComm.SimpleClient
{
using System.Threading.Tasks;
using log4net;
using SignalR.Client.Hubs;
class Program
{
private static readonly ILog logger = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
SignalRClient client = new SignalRClient("http://localhost:5001/");
client.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
logger.Error("Failed to start!", task.Exception.GetBaseException());
}
else
{
logger.InfoFormat("Success! Connected with client connection id {0}", client.ConnectionId);
// Do more stuff here
client.Invoke("Register", "Test").ContinueWith(tsk =>
{
if (tsk.IsFaulted)
logger.Error("Failed to start!", tsk.Exception.GetBaseException());
else
logger.Info("Success! Registered!");
});
}
});
System.Console.WriteLine("Press Enter to close...");
System.Console.ReadLine();
client.Invoke("Unregister", "Test").ContinueWith(tsk =>
{
if (tsk.IsFaulted)
logger.Error("Failed to stop!", tsk.Exception.GetBaseException());
else
logger.InfoFormat("Success! Unregistered!");
});
client.Stop();
}
}
public class SignalRClient : HubConnection
{
private static readonly ILog logger = LogManager.GetLogger(typeof(SignalRClient));
IHubProxy hub = null;
public SignalRClient(string url)
: base(url)
{
hub = CreateProxy("Test.SignalRComm.SimpleServer.SignalRTestHub");
}
public Task Invoke(string methodName, params object[] args)
{
return hub.Invoke(methodName, args);
}
public void AddMessage(string data)
{
logger.InfoFormat("Received {0}!", data);
}
}
}
While invoking hub methods from client (Register and Unregister) works fine, I'm not able to call client AddMessage method from hub.
Furthermore the Disconnect method of the hub is never called when a client is closed.
What I'm doing wrong? I'm not able to find any working example.
Edit
Subscribing to hubs events on the client like this:
hub.On<string>("Notify", message => Console.Writeline("Server sent message {0}", message);
and triggering the event on the hub like this:
Clients.Notify("Something to notify");
makes the notifications from server to clients working.
I'm still unable to detect a client disconnection. I implemented the IDisconnect interface on the hub, but when a client connection stops, the Disconnect method on the hub isn't triggered.
Thanks for your help.
Take a look at how to use the .NET client here:
https://gist.github.com/1324342
And API docs here:
https://github.com/SignalR/SignalR/wiki
TL;DR you need to subscribe to specific methods, deriving from the hubConnection doesn't make any magic happen.

WCF server/client callbacks, reply from client to server

In my client/server application, I want count other value in everyone client.
I made application using callbacks, but something is wrong. I get Exception, when I want call method pipeproxy.polacz(S); Which get value to server and write in server console now.
Exception is:
This operation would deadlock because the reply cannot be received until the current Message completes processing. If you want to allow out-of-order message processing, specify ConcurrencyMode of Reentrant or Multiple on CallbackBehaviorAttribute.
Other problem is, how sum resault in this funkction from all clients.
example;
client 1: S = 1;
client 2: S = 2;
client 3: S = 3;
And this function take result from all clients and sum it. So server will write 6 in server console.
My application code:
server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Interface;
namespace WCFapp
{
class Program
{
static void Main(string[] args)
{
Klienci cust = new Klienci();
cust.Connect();
}
}
}
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interface;
namespace WCFapp
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class Klienci : IMessage
{
private static List<ImessageCallback> subscribers =
new List<ImessageCallback>();
public void lista()
{
string nm = Console.ReadLine();
if (nm == "1")
{
Console.WriteLine("Number of conected clients: " + subscribers.Count());
funkcja();
}
}
public void Connect()
{
using (ServiceHost host = new ServiceHost(
typeof(Klienci), new Uri("net.tcp://localhost:8000")))
{
host.AddServiceEndpoint(typeof(IMessage),
new NetTcpBinding(), "ISubscribe");
try
{
host.Open();
lista();
Console.ReadLine();
host.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
public bool Subscribe()
{
try
{
ImessageCallback callback = OperationContext.Current.GetCallbackChannel<ImessageCallback>();
if (!subscribers.Contains(callback))
subscribers.Add(callback);
Console.WriteLine("Client is conected ({0}).", callback.GetHashCode());
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}
public bool Unsubscribe()
{
try
{
ImessageCallback callback = OperationContext.Current.GetCallbackChannel<ImessageCallback>();
if (subscribers.Contains(callback))
subscribers.Remove(callback);
Console.WriteLine("Client is unconected ({0}).", callback.GetHashCode());
return true;
}
catch
{
return false;
}
}
public void funkcja()
{
int a = 1; int b = 3;
subscribers.ForEach(delegate(ImessageCallback callback)
{
if (((ICommunicationObject)callback).State == CommunicationState.Opened)
{
Console.WriteLine("a= {0} , b= {1}", a, b);
callback.klient_licz(a, b);
a++;
b++;
}
});
}
public void polacz(int S)
{
Console.WriteLine("Sum: {0}", S);
}
}
}
Interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Interface
{
[ServiceContract(CallbackContract = typeof(ImessageCallback), SessionMode = SessionMode.Required)]
public interface IMessage
{
[OperationContract]
void funkcja();
[OperationContract]
void polacz(int S);
[OperationContract]
bool Subscribe();
[OperationContract]
bool Unsubscribe();
}
[ServiceContract]
public interface ImessageCallback
{
[OperationContract]
void klient_licz(int a, int b);
}
}
Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Interface;
namespace Client
{
class Program
{
static void Main(string[] args)
{
clients cl = new clients();
if (cl.Conect() == true)
{
string tmp = Console.ReadLine();
while (tmp != "EXIT")
{
cl.SendMessage(tmp);
tmp = Console.ReadLine();
}
}
cl.Close();
Environment.Exit(0);
}
}
}
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Interface;
namespace Client
{
class clients : ImessageCallback, IDisposable
{
IMessage pipeProxy = null;
public bool Conect()
{
DuplexChannelFactory<IMessage> pipeFactory =
new DuplexChannelFactory<IMessage>(
new InstanceContext(this),
new NetTcpBinding(),
new EndpointAddress("net.tcp://localhost:8000/ISubscribe"));
try
{
pipeProxy = pipeFactory.CreateChannel();
pipeProxy.Subscribe();
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}
public void Close()
{
pipeProxy.Unsubscribe();
}
public void klient_licz(int a, int b)
{
int S = a + b;
Console.WriteLine("Sum= {0}", S);
pipeProxy.polacz(S); //ERROR
}
}
}
The issue here is that inside your callback method klient_licz (which is called by the server) you are making another server call. This is not allowed the way your contracts are currently setup.
Check you really need this behaviour. Do you really need to make a server call INSIDE a method on the callback interface (klient_licz).
If you do need this behaviour then you might be able to fix things by marking the klient_licz call OneWay on the callback interface. That will mean that server call to the callback will not block until the client returns (which is what is currently causing your issue because the server is waiting for the client call to return but the client call is waiting on a call to the server):
[ServiceContract]
public interface ImessageCallback {
[OperationContract(IsOneWay = true)]
void klient_licz(int a, int b);
}
Alternatively you could mark the callback implimentation with a concurrancy mode other than the default mode Single. Eg Reentrant as follows - but bear in mind that this means that calls to callback will not long be marshalled to the UI thead ie will be on threadpool threads so you would have to dispatch to update the UI from method on the callback interface:
[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
class clients : ImessageCallback, IDisposable {
...
}
If you want to understand ConcurrencyMode and how it effects execution then you will really need to do someback ground reading as it does get a little complicated - but if you dont have that background it is difficult to really understand what is happen when you change the ConcurrencyMode. This dasBlonde blog post has a good summary of the different modes and behaviour - but you might want to start with some tutorials that are a bit more beginner orientated.

Getting callers IP

I have application based on this tutorial
Method I use to test connection to server (in client app):
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
}
Service main function:
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() function decaration
[ServiceContract(Namespace = "http://PBMB")]
public interface IService
{
[OperationContract]
string Ping();
}
Ping() function implementation
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.";
}
}
How can I put caller's IP in Message method?
The original blog is available through the Wayback Machine. Note that you'll need to be using WCF 3.5 or later per the author's post.
The code from the article is below;
Service Contract
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);
}
}
Implementation with retrieving 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);
}
}
}
Are you looking for something like
HttpContext.Current.Request.UserHostAddress

Categories