当前位置: 首页 > 知识库问答 >
问题:

如何连续地从套接字接收数据?

葛修筠
2023-03-14

我试图通过Windows服务从套接字接收数据,但当我建立连接时,它会立即生效。我希望不断地接收它(当端口关闭时,它将断开连接)。我怎样才能做到这一点?

这是我现在的输出;

“GET/HTTP/1.1

主持人:127.0.0.1:1994

连接:保持活力

缓存控制:最大年龄=0

升级-不安全-请求: 1

用户代理:Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/51.0.2704.106 Safari/537.36

接受:text/html,应用程序/xhtml xml,应用程序/xml; q=0.9, Image/webp,/; q=0.8

接受-编码: gzip,缩小, sdch

接受语言:tr,tr;q=0.8,在美国;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";
        }
    }
}

共有1个答案

孙洋
2023-03-14

为了连续接收数据,你实际上需要放入一些循环

例如:

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);

哪个wan不会阻止当前的线程

 类似资料:
  • 如果客户端侦听套接字,则在http://socketplaceonnet.com例如,它如何知道有新内容?我假设服务器无法直接向客户端发送数据,因为客户端可能位于路由器后面,没有端口转发,因此无法直接连接。客户端可能是一部移动电话,可以更改其IP地址。我理解,要让客户端成为侦听器,服务器不需要知道客户端的IP。 非常感谢。

  • socket_read和socket_recv之间有什么区别?我正在尝试使用PHP套接字,但使用socket_read时收到了以下警告: 请帮帮我!

  • 当我尝试接收大量数据时,它会被切断,我必须按enter键才能获取其余数据。起初,我可以增加一点,但它仍然不会收到所有的。正如您所看到的,我增加了conn.recv()上的缓冲区,但它仍然无法获取所有数据。它会在某一点切断它。我必须在原始输入上按enter键才能接收其余数据。我是否可以一次获取所有数据?这是密码。

  • 我使用Android应用程序通过TCP套接字与同一局域网上的PC java应用程序进行通信、发送和接收消息。下面是我在android中使用的Asynctask的代码,用于发送消息并从PC接收回复: } 我在onPostExcecute中的祝酒词中显示PC的回复。 Android通过BufferedWriter发送消息,而PC上的java应用程序在BufferedReader中接收消息。 PC在收到

  • 问题内容: 我写了一个小程序,可以在特定端口上与服务器交互。该程序可以正常运行,但是: 一旦程序意外终止,并且此套接字连接一直处于状态显示。如果我尝试运行程序,它将挂起,并且必须强制将其关闭,这会累积 更多的 套接字连接。 有没有一种方法可以清除这些连接? 问题答案: 表示您的程序仍在运行,并且尚未关闭套接字(内核正在等待它关闭)。添加到以获取该pid,然后更加有力地将其杀死(如果需要,可以将其删

  • 我写了一个与特定端口上的服务器交互的小程序。程序运行良好,但是: 一旦程序意外终止,从那以后套接字连接就显示为状态。如果我试图运行一个程序,它就挂起,我必须强制关闭它,这会积累更多的套接字连接。 有办法冲洗这些连接吗?