使用Windows服务从C#Asp Server获取数据

时间:2017-11-07 14:43:31

标签: c# tcp

我有一个Windows服务,每秒循环并通过连接HTTPS并发送“自制的”加密数据并接收响应来轮询服务器(在ASP WebForms Framework 4中,而不是MVC中)获取新信息,加密为好。

这种方法的问题是资源和时间消耗。

每一秒,服务都必须创建连接,加密数据并解密响应。

我在考虑使用TcpConnections:

  • 一劳永逸地连接到服务器
  • 当服务器到来时从服务器接收新信息并在我的服务中对其进行处理

我试图这样做,就像这样:

服务器端代码(目前在Global.asax中)

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

   Task.Run(Run);
}

public static async Task Run()
{
    try
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8080); //Any IPAddress that connects to the server on any port
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Initialize a new Socket

        socket.Bind(ip); //Bind to the client's IP
        socket.Listen(10); //Listen for maximum 10 connections
        Console.WriteLine("Waiting for a client...");
        Socket client = socket.Accept();
        IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
        Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);

        string welcome = "Welcome"; //This is the data we we'll respond with
        byte[] data = new byte[1024];
        data = Encoding.ASCII.GetBytes(welcome); //Encode the data
        client.Send(data, data.Length, SocketFlags.None); //Send the data to the client
    } 
    catch(Exception e)
    {
        Console.WriteLine($"Error : {e.Message} {e.StackTrace}");
    }
}

(还创建了一种方法,用于将数据发送到上述任务之外的客户端。)

客户端代码

const int PORT_NO = 8080;
const string SERVER_IP = "localhost";

static void Main()
{

    IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);

    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    try
    {
        server.Connect(ip); //Connect to the server
    }
    catch (SocketException e)
    {
        Console.WriteLine($"Unable to connect to server : {e.Message} {e.StackTrace}");
        return;
    }

    Console.WriteLine("Type 'exit' to exit.");
    while (true)
    {
        string input = "aaaaa";
        if (input == "exit")
            break;
        server.Send(Encoding.ASCII.GetBytes(input)); //Encode from user's input, send the data
        byte[] data = new byte[1024];
        int receivedDataLength = server.Receive(data); //Wait for the data
        string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); //Decode the data received
        Console.WriteLine(stringData); //Write the data on the screen
        System.Threading.Thread.Sleep(5000);
    }


}

连接似乎适用于第一条消息,我设法从客户端和服务器发送/接收数据。但随后'客户端'服务器端对象自行处理(变为空)。

  • 是因为Tcp连接不是持久的吗?

如果是这样,我试图添加这一行:

socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);

但后来我得到以下异常:

An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call
  • 如何在客户端收到服务器发送的数据后阻止我的TcpConnection关闭?

  • 是否有更安全的方式将数据从服务器交换到客户端?也许通过使用这样的SSL TLS连接:C# TcpClient reading multiple messages over persistent connection?我在考虑SignalR,但我不确定它是否适用于Framework 4 Web App环境

0 个答案:

没有答案