C#socket传送文件问题
heipo 2007-09-20 11:50:37 小弟最近用C#编程,有个问题向请教各位,希望各位给指点一下!
,文件名可以传过去,但文件内容是空的
C#发文件主要代码:(是不是SentFile.Read有问题)
public void SendFile(string filename)
{
try
{
SentFile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);//建立将发送文件的只读FileStream实例
int nPos = filename.LastIndexOf("\\");
if (nPos > -1)
filename = filename.Substring(nPos + 1);//查找不含路径的文件名
string fileinfo;
fileinfo = "\x01\x53" + SentFile.Length.ToString() + "\x03" + filename + "\x04";
bSendFile = true;
SendData(fileinfo);//发送含有命令信息和文件名、文件长度信息的字符串
}
catch (Exception err)
{
CloseSendFile();
RaiseSockErrEvent("File : " + filename + " Error:" + err.Message);
return;
}
}
/// <summary>
/// 发送字节信息
/// </summary>
/// <param name="data">字节数组</param>
/// <param name="dataLen">数据长度</param>
private void SendbyteData(byte[] data, int dataLen)
{
try
{
Soc.BeginSend(data,0,dataLen,SocketFlags.None,new AsyncCallback(SendFileCallback), Soc);
}
catch (Exception e)
{
RaiseSockErrEvent("Send : " + e.Message);
CloseSocket();
}
}
/// <summary>
/// 开始发送文件
/// </summary>
private void StartSendFile()
{
byte[] buff = new byte[512];
try
{
if (SentFile.Length != SentFile.Position)
{
int nRead = SentFile.Read(buff, 0, 512);
if (nRead > 0)
SendbyteData(buff, nRead);
}
}
catch (Exception err)
{
RaiseSockErrEvent("Send File: Error:" + err.Message);
}
}
/// <summary>
/// 发送文件信息
/// </summary>
/// <param name="strCmd">包含文件名和长度的字符串</param>
/// <param name="nPos">第一控制信息所在位置</param>
private void SentFileStatus(string strCmd, int nPos)
{
int nPos2 = strCmd.IndexOf("\x03");
int nCommand;
if (nPos2 > -1)
nCommand = Convert.ToInt32(strCmd.Substring(nPos + 2, nPos2 - nPos - 2));
else return; //back, cause the command string not fully received yet
switch (nCommand)
{
case 2101:
RaiseMessageEvent("File is sent.. ");
break;
case 3100:
nTtlByteSend = 0;
StartSendFile();
break;
case 3103:
case 3104:
if (SentFile != null)
{
RaiseMessageEvent("Fail to send file " + SentFile.Name);
SentFile.Close();//Remote PC reject this file, so close it.
}
break;
case 3105:
if (SentFile != null)
{
RaiseMessageEvent("Sending " + SentFile.Name + " rejected");
SentFile.Close();
}
break;
}
if (nPos2 > 1)
response.Remove(nPos, nPos2 - nPos + 1);
}
}
C接收端代码:
printf("Please input the file's name():");
scanf("%s",sdbuf);
strcpy(filename,sdbuf);
if((send(nsockfd,filename,sizeof(filename),0))==-1)
{
printf("send error\n");
return(0);
}
printf("giving\n");
fp=fopen("y","r");
if(fp<0)
printf("cannot open the file %s\n",strerror(errno));
fread(sdbuf,sizeof(sdbuf),20,fp);
send(nsockfd,sdbuf,sizeof(sdbuf),0);
printf("over\n");