用SOCKET发送文件导致界面不响应
Thread t = new Thread(new ThreadStart(TransferFile));
t.IsBackground = true;
t.Start();
-----------------
private void TransferFile()
{
FileStream fs = new FileStream (this.m_files2,FileMode.Open,FileAccess.Read,FileShare.Read);
IPAddress ip = IPAddress.Parse(ReceIP); //对方IP
IPEndPoint endPoint = new IPEndPoint(ip,1002);
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
socket.Connect(endPoint);
int iCount = (int)fs.Length;
byte[] buf = new byte[iCount];
int iSended = 0; //已经发送的字节数
int iSending = 0;
int iBlock =1024;
byte[] msg = new byte[2];
int i = 0;
bool error = false;
fs.Read(buf,0,iCount);
while(iSended < iCount)
{
if (iSended + iBlock <= iCount)
iSending = iBlock ;
else
iSending = iCount - iSended;
socket.Send(buf,iSended,iSending,SocketFlags.None);
socket.Receive(msg);
while(Encoding.ASCII.GetString(msg) != "ok")
{
i++;
Thread.Sleep(100);
socket.Receive(msg);
if (i==20)
{
MessageBox.Show("传送文件超时","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
error = true;
break;
}
}
i=0;
iSended += iSending;
}
fs.Close();
socket.Shutdown(SocketShutdown.Both);
socket.Close();
if (error == true)
this.Close();
else
MessageBox.Show("传送文件完成","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
文件发送成功了,发送方的界面就不响应了,接收方的界面是好的,本窗体是用ShowDialog打开的