如何在没有代理的情况下调用自托管TCP服务?

时间:2019-07-25 01:29:46

标签: c# tcpclient self-hosting tcpserver

我创建了一个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(...)

  

有关如何实现此目标的任何线索或建议?

1 个答案:

答案 0 :(得分:0)

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

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

相关问题