110,534
社区成员
发帖
与我相关
我的任务
分享
private void Listener() //开始监听传输请求
{
IPHostEntry ipHostInfo =Dns.Resolve(System.Net.Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
this._ls =new TcpListener (ipAddress,6688);
this._ls .Start ();
while(true)
{
Socket socket=this._ls .AcceptSocket ();
this.txtConnect .Text =socket.RemoteEndPoint .ToString ();
Receive(socket); //调用接受文件函数
}
}
//我在每个字节块的前面加入了一个int型的变量,它表示每次发送文件数据的长度
private void Receive(Socket socket) //接受文件函数
{
NetworkStream ns = new NetworkStream(socket);
FileStream fs = new FileStream("c:\\file.txt", FileMode.OpenOrCreate);
bool isRead = true;
while (isRead)
{
int count = ns.Read(this._receiveBuf, 0, this._receiveBuf.Length);
int datanum = 0;
datanum = BitConverter.ToInt32(this._receiveBuf, 0);
if (datanum > 0) //如果传输的文件字节数>0 证明还有数据没有传输完
{
fs.Write(this._receiveBuf, 4, datanum);
fs.Flush();
}
else //datanum = 0 ,文件发送完毕
{
isRead = false;
}
}
this.txtFile.Text = "文件传输成功";
fs.Close();
}
private void btSend_Click(object sender, System.EventArgs e) //点击按钮后开始传输
{
if (this._isConnect)
{
_ns = _tc.GetStream();
string path = this.txtPath.Text.Trim();
FileStream fs = new FileStream(path, FileMode.Open);
int sendCount = 0;
byte[] countbuffer = null;
byte[] clientbuffer = new byte[1004];
while (sendCount < fs.Length && _ns.CanWrite)
{
int count = fs.Read(_sendBuf, 0, _sendBuf.Length); //从文件中读出数据
countbuffer = BitConverter.GetBytes(count); //表示每次读出了多少字节数
countbuffer.CopyTo(clientbuffer,0); //将count加入数组首部
_sendBuf.CopyTo(clientbuffer, 4);
this._ns.Write(clientbuffer, 0, 4 + count); //写入网络流
sendCount += count;
}
countbuffer = BitConverter.GetBytes(0); //发送文件完后,读出字节数为0
this._ns.Write(countbuffer, 0, countbuffer.Length);
_ns.Close();
fs.Close();
}
}