实现像飞鸽一样的文件传输功能

本文详细介绍了使用C#.NET Socket在服务器端和客户端之间实现文件传输的过程,包括创建socket对象、绑定端口、监听连接、接收文件数据、保存文件等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务端:

//FILE TRANSFER USING C#.NET SOCKET - SERVER
class FTServerCode
{
IPEndPoint ipEnd;

Socket sock;
public FTServerCode()
{
ipEnd = new IPEndPoint(IPAddress.Any, 5656);

//Make IP end point to accept any IP address with port no 5656.

sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

//Here creating new socket object with protocol type and transfer data type
sock.Bind(ipEnd);

//Bind end point with newly created socket.
}
public static string receivedPath;
public static string curMsg = "Stopped";
public void StartServer()
{
try
{
curMsg = "Starting...";
sock.Listen(100);
/* That socket object can handle maximum 100 client connection at a time & waiting for new client connection /
curMsg = "Running and waiting to receive file.";
Socket clientSock = sock.Accept();
/* When request comes from client that accept it and return new socket object for handle that client. */
byte[] clientData = new byte[1024 * 5000];

int receivedBytesLen = clientSock.Receive(clientData);
curMsg = "Receiving data...";

int fileNameLen = BitConverter.ToInt32(clientData, 0);

/* I’ve sent byte array data from client in that format like [file name length in byte][file name] [file data], so need to know first how long the file name is. /
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
/* Read file name */
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath +"/"+ fileName, FileMode.Append)); ;

/* Make a Binary stream writer to saving the receiving data from client. /
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
/* Read remain data (which is file content) and save it by using binary writer. */
curMsg = "Saving file...";

bWrite.Close();
clientSock.Close();

/* Close binary writer and client socket */
curMsg = "Reeived & Saved file; Server Stopped.";
}
catch (Exception ex)
{
curMsg = "File Receving error.";
}
}
}

</code>

客户端:

<code>

//FILE TRANSFER USING C#.NET SOCKET - CLIENT
class FTClientCode
{
public static string curMsg = "Idle";
public static void SendFile(string fileName)
{
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);

/* Make IP end point same as Server. */
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
/* Make a client socket to send data to server. */

string filePath = "";
/* File reading operation. */
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}


byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
if (fileNameByte.Length > 850 * 1024)
{
curMsg = "File size is more than 850kb, please try with small file.";
return;
}

curMsg = "Buffering ...";
byte[] fileData = File.ReadAllBytes(filePath + fileName);

/* Read & store file byte data in byte array. */
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];

/* clientData will store complete bytes which will store file name length, file name & file data. */
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
/* File name length’s binary data. */
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
/* copy these bytes to a variable with format line [file name length][file name] [ file content] */
curMsg = "Connection to server ...";
clientSock.Connect(ipEnd);

/* Trying to connection with server. /

curMsg = "File sending...";
clientSock.Send(clientData);
/* Now connection established, send client data to server. */
curMsg = "Disconnecting...";
clientSock.Close();

/* Data send complete now close socket. */
curMsg = "File transferred.";

}
catch (Exception ex)
{
if(ex.Message=="No connection could be made because the target machine actively refused it")
curMsg="File Sending fail. Because server not running." ;
else
curMsg = "File Sending fail." + ex.Message;


}
}

</code>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值