我用socket做二进制流的局域网文件传送出了bug
用的是vs2012 语言:C#bug是我服务端发给客户端一个xml文件,客户端接收到后没有内容而且是资源被客户端占用 删除都不行,必须关闭客户端以后接收到的xml才有内容,而且可以正常打开删除。部分代码如下:
发送文件:
private void ReceiveMes(object so)
{
Socket soClient = so as Socket;
IPEndPoint ClBin = (IPEndPoint)soClient.RemoteEndPoint;
string message = string.Empty;
string toip = string.Empty;
while (true)
{
try
{
byte[] data = new byte[1024];
int length = soClient.Receive(data);
message = Encoding.UTF8.GetString(data, 0, length);
txtContent.Dispatcher.Invoke(new Action(() => { this.txtContent.AppendText(message + "\r\n"); }));
toip = message.Substring(message.LastIndexOf(' ') + 1);
Socket SendKet = GetSendKet(toip);
if (message.Equals("Message "+toip))
{
byte[] mes = Encoding.UTF8.GetBytes("Message");
SendKet.Send(mes);
FileStream fileSteam = new FileStream("Message.xml", FileMode.OpenOrCreate, FileAccess.Read);
///文件大小
Byte[] fsSize = new Byte[fileSteam.Length];
///读取文件的二进制流
BinaryReader reader = new BinaryReader(fileSteam);
///读取数据
reader.Read(fsSize, 0, (int)fileSteam.Length);
///发送数据
try
{
SendKet.Send(fsSize);
}
catch
{
MessageBox.Show("服务器忙,请稍后再发!");
}
///关闭文件流
fileSteam.Close();
//SendKet.LingerState.Enabled = false;
}
接收文件:
private void Recevie()
{
while (true)
{
try
{
byte[] message = new byte[1024];
int length = ketOne.Receive(message);
string mes = Encoding.UTF8.GetString(message, 0, length);
if (mes.Equals("Message"))
{
int i = 0;
int bytes = 0;
Byte[] recData = new Byte[1024];
///创建一个新文件保存接收的数据
string Messages = "Message.xml";
FileStream fileStream = new FileStream(Messages, FileMode.OpenOrCreate);
BinaryWriter writer = new BinaryWriter(fileStream);
while (true)
{
bytes = ketOne.Receive(recData, recData.Length,0);
//读取完成后退出循环
i += bytes;
if (bytes <= 0)
{
break;
}
writer.Write(recData, 0, bytes);
}
///关闭写文件流
fileStream.Close();
writer.Close();
//ketOne.Shutdown(SocketShutdown.Receive);
//ketOne.Close();
C# socket wpf --------------------编程问答-------------------- 而且我连续接收这个文件的话 内容会在原来的基础上追加 --------------------编程问答-------------------- 调试看FileStream有没有close --------------------编程问答-------------------- 你要采用垃圾处理机制,用完后要释放
补充:.NET技术 , C#