新手C# SOCKET编程,关于RECEIVE的一些问题
感谢各位达人光临此帖!
在下新手学用C#进行SOCKET编程,关于FTP的例子已经看了些,也实践了些,不过有个问题想问问...
在进行接收远程FTP服务器响应消息时,用receive函数常常出现接收消息不完整,具体表现问:连接本机或响应快的FTP服务器,基本没问题,但是如果连接国外的FTP服务器,显示文件列表收到的消息常常不完整,而且在有较长欢迎消息的设置时,也会接收有问题。
这是两个函数:
1.接收命令返回的响应消息
private void readResponse()
{
this.rmsg = " ";
this.response = this.readLine();
}
private string readLine()
{
while (true)
{
this.bytes = clientSocket.Receive(this.buffer, this.buffer.Length, 0);
this.rmsg += System.Text.Encoding.Default.GetString(this.buffer, 0, this.bytes);
if (this.bytes < this.buffer.Length)
{
break;
}
}
string[] msg = this.rmsg.Split( '\n ');
for(int i = 0; i < msg.Length - 2; i ++)
{
ShowMsg(msg[i], true); //直接将所得的消息除最后一行外显示在LISTVIEW控件中
}
//判断是否是最后一条响应消息,非其他信息
if (this.rmsg.Length > 2)
this.rmsg = msg[msg.Length - 2];
else
this.rmsg = msg[0];
if (this.rmsg.Length > 4 && !this.rmsg.Substring(3, 1).Equals( " "))
{
response = this.readLine();
}
return rmsg;
}
2.接收服务器返回的文件列表消息
this.rmsg = " ";
DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);
while (timeout > DateTime.Now)
{
this.bytes = cSocket.Receive(buffer, buffer.Length, 0);
this.rmsg += System.Text.Encoding.Default.GetString(buffer, 0, bytes);
if (this.bytes < this.buffer.Length)
{
cSocket.Close();
break;
}
}
望高手赐教!小弟先谢过了!
[解决办法]
while (true)
{
}
改为异步处理试试,就是用beginReceive