将通过套接字接收到的数据写入文件

我正在尝试使用 TCP 客户端或套接字从 IP 地址和端口收集数据,但似乎无法找到将接收到的内容成功写入控制台或文件的方法。在我在线筛选的众多来源中,包括 MSDN 文档和各种博客,我发现这个是最容易理解的,但它仍然没有向控制台写入任何内容,而且我知道 IP 地址/端口(我可以't share) 应该向我发送数据流。


我究竟做错了什么?


using System;

using System.Net;

using System.Net.Sockets;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Diagnostics;


namespace TCPIPChallenge

{

    public class Program

    {

        public static void Main(string[] args)

        {

            Client client = new Client();

            client.SetupServer();

        }

    }


    public class Client

    {


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

        private byte[] _recieveBuffer = new byte[8142];


        private void SetupServer()

        {

            try

        {

            _clientSocket.Connect(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8888));

            Console.WriteLine("It was successful!");

        }

        catch (SocketException ex)

        {

            Console.WriteLine("There was an issue...");

            Debug.Write(ex.Message);

        }

        Console.WriteLine(_clientSocket.Connected);

        _clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);


    }


    private void ReceiveCallback(IAsyncResult AR)

    {

        //Check how much bytes are recieved and call EndRecieve to finalize handshake

        int recieved = _clientSocket.EndReceive(AR);

        Console.WriteLine(_clientSocket.Connected);

        if (recieved <= 0)

            return;


            //Copy the recieved data into new buffer , to avoid null bytes

            byte[] recData = new byte[recieved];

            Buffer.BlockCopy(_recieveBuffer, 0, recData, 0, recieved);


            //Process data here the way you want , all your bytes will be stored in recData

            Console.WriteLine(recData.ToString());


            //Start receiving again

        }

    }

}


30秒到达战场
浏览 183回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP