【问题标题】:How to call self-hosted TCP service without proxy?如何在没有代理的情况下调用自托管 TCP 服务?
【发布时间】:2019-07-25 01:29:46
【问题描述】:

我创建了一个C# Self-hosted TCP service,其服务器代码如下:

static void Main(string[] args)
        {
            var uris = new Uri[1];
            string address = "net.tcp://localhost:4345/DeviceService";
            uris[0] = new Uri(address);

            IDeviceService service = new DeviceService();
            ServiceHost host = new ServiceHost(service, uris);
            var binding = new NetTcpBinding(SecurityMode.None);
            host.AddServiceEndpoint(typeof(IDeviceService), binding, "");
            host.Opened += Host_Opened;
            host.Open();
            Console.ReadLine();

        }

DataService 类有如下代码:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class DeviceService : IDeviceService
    {

        public byte[] ProcessMessage(byte[] message)
        {
            try
            {
                string data = Encoding.ASCII.GetString(message);

            }
            catch
            {
                LogHelper.Log(LogTarget.File, "Error decoding message.");
            }


            byte[] bytes = Encoding.ASCII.GetBytes("This is a message reply");

            return bytes;
        }
    }

现在,为了从客户端调用它,我有以下代码:

static void Main(string[] args)
        {
            Console.WriteLine("Press any key to enter");
            Console.ReadLine();

            var uri = "net.tcp://xx.xx.xx.xx:4345/DeviceService";
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
            var channel = new ChannelFactory<IDeviceService>(binding);
            var endPoint = new EndpointAddress(uri);
            var proxy = channel.CreateChannel(endPoint);

            byte[] bytes = Encoding.ASCII.GetBytes("This is a message send");

            var response = proxy.ProcessMessage(bytes);

            string data = Encoding.ASCII.GetString(response);

            Console.WriteLine(data);

            Console.ReadLine();

        }

我遇到的问题是我们想在不创建代理的情况下调用这个 TCP 服务。我们希望通过调用 IP 地址和端口来向这个 TCP 套接字服务发送数据,而不需要尝试创建代理并执行 proxy.ProcessMessage(...)

关于如何实现这一点的任何线索或建议?

【问题讨论】:

    标签: c# tcpclient self-hosting tcpserver


    【解决方案1】:

    我认为这是不可能的,因为它违反了WCF 的概念。您必须使用代理来允许 WCF 为您处理大量内部人员,例如消息框架、多路复用等。

    如果您想使用原始套接字 - 只需使用它们。 TcpListener + TcpClientSocket 本身。还要检查 github 上的项目,例如 simplsockets

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多