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

时间:2018-06-12 01:48:29

标签: c# sockets tcpclient

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

我做错了什么?

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
            _clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您好像不在等待结果显示。放一个Console.Read();在你的主要。

public static void Main(string[] args)
        {
            Client client = new Client();
            client.SetupServer();
            Console.Read();
        }

答案 1 :(得分:1)

这似乎是这里的嫌疑人:

Console.WriteLine(recData.ToString());

不能只在字节数组上调用ToString,希望它变成一个字符串,因为有许多不同类型的编码可以将字节转换为字符串,反之亦然。某些编码占用的字节数多于其他编码,例如UTF-8和UTF-16。

使用Unicode编码的示例

将邮件转换为字节:

byte[] data = System.Text.Encoding.Unicode.GetBytes("Hello!");

再次显示数据:

byte[] recData = new byte[recieved];
string message = System.Text.Encoding.Unicode.GetString(recData);
Console.WriteLine(message); // "Hello!"

确保在服务器端和客户端使用类似的编码来获取一致的数据。

不同的编码类型:UTF-8, UTF-16, and UTF-32