c# - 在 .net c# 中使用 ssl Stream 从 Tcp.Client.Socket 发送数据

标签 c# sockets ssl tcp sslstream

我尝试读取一个 xml 文件并使用 sslStream 发送到服务器。 在发送到服务器之前,我必须登录并在成功授权后我必须发送文件数据。到fileSize大约是300kb。 我可以让 sycessfull 登录,但问题是服务器似乎没有收到我发送的数据。这是代码 method1:我成功登录(我收到 ok 但似乎我无法发送 xml 文件的内容)

TcpClient sendClient = new TcpClient(serverName, port);
        SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
        sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);

        sendStream.Write(Encoding.UTF8.GetBytes("Login\r\n" + username + "\r\n" + password + "\r\n"));
        sendStream.Flush();
        int bytes = -1;
        byte[] buffer = new byte[2048];

        bytes = sendStream.Read(buffer, 0, buffer.Length);

        string response = Encoding.UTF8.GetString(buffer, 0, bytes);

        if (response.Trim() == "OK")
        {
            MessageBox.Show("Connected");
            byte[] b1 = File.ReadAllBytes(filePath);
            sendStream.Write(Encoding.UTF8.GetBytes("Send\r\n"));
            sendStream.Write(Encoding.UTF8.GetBytes(fileName+"\r\n"));
            sendStream.Write(b1, 0, b1.Length);
            sendStream.Flush();
            sendStream.Write(Encoding.UTF8.GetBytes("Quit\r\n"));
            sendStream.Flush();
            sendClient.Close();
        }

这是使用 streamWriter 的第二种方法

TcpClient sendClient = new TcpClient(serverName, port);
        SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
        sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);

        StreamWriter writer = new StreamWriter(sendStream);
        writer.WriteLine("Login");
        writer.WriteLine(username);
        writer.WriteLine(password);
        writer.Flush();
        StreamReader reader = new StreamReader(sendStream);
        string response = reader.ReadLine();
        if (response.Trim() == "OK")
        {
            MessageBox.Show("succesfull connect");

            string allText = File.ReadAllText(filePath,Encoding.Default);
            writer.WriteLine("Send");
            writer.WriteLine(fileName);
            writer.WriteLine(allText);
            sendClient.Close();
        }

最佳答案

好的,一种解决方案是将所有命令写成一个字节数组,然后将它们复制到一个更大的数组中。诀窍是将 dataSize 添加为双字节序数

关于c# - 在 .net c# 中使用 ssl Stream 从 Tcp.Client.Socket 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33938586/

相关文章:

java - 使用 Pax(包括 Jetty)在 Apache Karaf 中启用/禁用允许的密码套件

c# - 如何增加 SQL 连接字符串的连接超时?

c# - 按特定顺序对 IQueryable 进行排序

c# - 在 csproj 中,我可以有条件地包含基于运行时标识符的文件吗?

multithreading - C++0x 线程和套接字

C编程-> wpa_supplicant连接-> udp广播发送到 "Network Unreachable"

c# - EndRead引发IO异常

c# - 对非相关实体进行复杂连接的 nhibernate queryover

c - SSLv23 不允许 sslv3 客户端连接

amazon-web-services - 为什么 Elastic Beanstalk 负载均衡器拒绝建立 SSL 连接?