【发布时间】:2015-12-07 16:30:01
【问题描述】:
我尝试使用 tcp 客户端的 sslStream 发送文件。文件大约 250kb。 当我不将 dataLength 写入流时,服务器会因为最大接收缓冲区大小而关闭连接。当我将dataLength写入流时,我没有例外,但服务器出现类型错误(连接正常关闭)。一个原因是,因为 Tcp 客户端关闭事件,服务器 无法接收我发送的数据;这是我的代码。服务器代码丢失,我知道它是用 indy 套接字库在 delphi 中编写的 这是我的代码
TcpClient sendClient = new TcpClient(serverName, port);
LingerOption lingerOption = new LingerOption(true, 20);
sendClient.LingerState = lingerOption;
using (SslStream sendStream = new SslStream(sendClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
{
try
{
sendStream.AuthenticateAsClient(serverName, null, SslProtocols.Ssl2, true);
sendStream.Write(Encoding.UTF8.GetBytes("Login\r\n" + username + "\r\n" + password + "\r\n"));
sendStream.Flush();
int bytesResp = -1;
byte[] buffer = new byte[1024];
bytesResp = sendStream.Read(buffer, 0, buffer.Length);
string response = Encoding.UTF8.GetString(buffer, 0, bytesResp);
if (response.Trim() == "OK")
{
sendStream.Write(Encoding.ASCII.GetBytes("Send\r\n"));
FileStream inputStream = File.OpenRead(filePath);
FileInfo f = new FileInfo(filePath);
int size = unchecked((int)f.Length);
byte[] byteSize = Encoding.ASCII.GetBytes(size.ToString());
sendStream.Write(byteSize);
sendStream.Write(Encoding.ASCII.GetBytes("\r\n"));
sendStream.Write(Encoding.ASCII.GetBytes(fileName + "\r\n"));
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
long sum = 0;
int count = 0;
byte[] data = new byte[1024];
while (sum < size)
{
count = fs.Read(data, 0, data.Length);
sendStream.Write(data, 0, count);
sum += count;
Array.Clear(data, 0, data.Length);
}
sendStream.Flush();
}
sendStream.Write(Encoding.UTF8.GetBytes("\r\n"));
sendStream.Write(Encoding.UTF8.GetBytes("Quit\r\n"));
}
MessageBox.Show("end the procedure");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (sendClient.Client.Connected)
{
sendClient.Client.Disconnect(false);
sendClient.Client.Dispose();
}
}
【问题讨论】:
标签: c# sockets tcp buffer sslstream