2016-06-29 18 views
1

Windowsサービス経由でソケットからデータを受信しようとしていますが、接続するとすぐにデータが送信されます。私はそれを絶えず受け取りたいです(ポートが閉じているときに切断されます)。どうすればこれを達成できますか?ソケットからデータを連続的に受信するにはどうしたらいいですか?

これは私の現在の出力です。

「GET/HTTP/1.1

ホスト:127.0.0.1:1994

接続:キープアライブ

Cache-Control:max-ageは= 0

アップグレード、安全でありません-requests:1

のUser-Agent:Mozillaの/ 5.0(Windows NTの10.0; Win64の、x64の)のAppleWebKit/537.36(KHTML、ヤモリなど)クローム/ 51.0.2704.106サファリ/ 537.36

受け入れ:テキスト/ HTMLを、アプリケーション/ XHTML + xmlの、アプリケーション/ XML、Q = 0.9、画像/ WEBP、/; Q = 0.8

は受け入れ-エンコーディング:GZIPを、収縮、SDCH

受け入れ言語:tr-TR、tr; q = 0.8、en-US; q = 0.6、en; q = 0.4

接続は続行されますか?偽」

using System; 
using System.IO; 
using System.Net; 
using System.Text; 
using System.Linq; 
using System.Threading; 
using System.Net.Sockets; 
using System.Diagnostics; 
using System.ComponentModel; 
using System.ServiceProcess; 
using System.Collections.Generic; 

namespace AServiceTest 
{ 
    public partial class Service1 : System.ServiceProcess.ServiceBase 
    { 
     Thread th; 
     bool isRunning = false; 
     byte[] bytes = new byte[1024]; 

     public Service1() 
     { 
      InitializeComponent(); 
     } 
     protected override void OnStart(string[] args) 
     { 
      th = new Thread(DoThis); 
      th.Start(); 
      isRunning = true;    
     } 
     private void DoThis() 
     { 
      while (isRunning) 
      { 
        Socket listener, connecter, acc; 
        listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
        connecter = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Variables 

        listener.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1994)); 
        listener.Listen(0); 

        acc = listener.Accept(); //Accepting comm with client part 
        bool IsConnected = !((listener.Poll(1000, SelectMode.SelectRead) && (listener.Available == 0)) || !listener.Connected); 

        File.AppendAllText(@"D:\Tasks\dataGathering.txt", Environment.NewLine + "Connection proceed?1 " + IsConnected); 


       new Thread(() => 
       { 

        byte[] bytes = new byte[1024]; 
        int byteCount = acc.Receive(bytes, SocketFlags.None); 

        File.AppendAllText(@"D:\Tasks\dataGathering.txt", Environment.NewLine + "Connection proceed?2 " + IsConnected); 

        Console.WriteLine(Encoding.UTF8.GetString(bytes)); //It encodes before writing to the screen 
        File.AppendAllText(@"D:\Tasks\dataGathering.txt", Environment.NewLine + " " + Encoding.UTF8.GetString(bytes)); 

        File.AppendAllText(@"D:\Tasks\dataGathering.txt", Environment.NewLine + "Connection proceed?3 " + IsConnected); 


        File.AppendAllText(@"D:\Tasks\dataGathering.txt", Environment.NewLine + "Connection proceed? " + IsConnected); 
        Console.WriteLine("Does connection proceeding? " + IsConnected); 

       }).Start(); 
      } 
     }   
     protected override void OnStop() 
     { 
      isRunning = false; 
      th = null; 
     } 
     private void InitializeComponent() 
     { 
      this.ServiceName = "AServiceTest"; 
      this.CanStop = true; 
      this.AutoLog = false; 
      this.EventLog.Log = "Application"; 
      this.EventLog.Source = "Service1"; 
     } 
    } 
} 

答えて

3

は、あなたが実際にいくつかのループに配置する必要が連続してデータを受信するには、例えば

:。

private void StartProcessing(Socket serverSocket) 
{ 
    var clientSocket = serverSocket.Accept(); 
    StartReceiveing(clientSocket); 
} 

private void StartReceiveing(Socket clientSocket) 
{ 
    const int maxBufferSize = 1024; 

    try 
    { 
     while (true) 
     { 
      var buffer = new byte[maxBufferSize]; 

      var bytesRead = clientSocket.Receive(buffer); 

      if (ClientIsConnected(clientSocket)) 
      { 
       var actualData = new byte[bytesRead]; 

       Array.Copy(buffer, actualData, bytesRead); 
       OnDataReceived(actualData); 
      } 
      else 
      { 
       OnDisconnected(clientSocket); 
      } 
     } 
    } 
    catch (SocketException ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 
} 

private void OnDisconnected(Socket issuedSocket) 
{ 
    if (issuedSocket != null) 
    { 
     issuedSocket.Shutdown(SocketShutdown.Both); 
     issuedSocket.Close(); 

     StartProcessing(listener); 
    } 
} 

private void OnDataReceived(byte[] data) 
{ 
    //do cool things 
} 

private static bool ClientIsConnected(Socket socket) 
{ 
    return !(socket.Poll(1000, SelectMode.SelectRead) && socket.Available == 0); 
} 

また、あなたのケースでは、私はおよそsocket async APIとタスクについてを読んでみて非同期プログラミングのような、クールでクリーンなものを実行することができます:

await Task.Factory.FromAsync(serverSocket.BeginAccept, result => serverSocket.EndAccept(result), serverSocket); 

あなたの現在のあなたをブロックしないでくださいThread

関連する問題