【发布时间】:2015-03-30 19:27:57
【问题描述】:
我在互联网上进行了一些研究后编写了该代码,以通过同一网络中的计算机发送文件。但是,有时它发送的文件已损坏或质量低下(如果文件是图片)。你能看看这个吗? 注意:我只想发送 10MB 大小的文件。
服务器
class Server
{
IPEndPoint end;
Socket sock;
public Server()
{
end = new IPEndPoint(IPAddress.Any, 5656);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(end);
}
public static string path;
public static string MsgCurrent = "Stopped";
public void StartServer()
{
try
{
MsgCurrent = "Starting...";
sock.Listen(100);
MsgCurrent = "Works and looks for files";
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024 * 1024 * 10]; //count per byte
int receivedByteLen = clientSock.Receive(clientData);
MsgCurrent = "Receiving file ...";
int fNameLen = BitConverter.ToInt32(clientData, 0);
string fName = Encoding.ASCII.GetString(clientData, 4, fNameLen);
BinaryWriter write = new BinaryWriter(File.Open(path + "/" + fName, FileMode.Append));
write.Write(clientData, 4 + fNameLen, receivedByteLen - 4 - fNameLen);
MsgCurrent = "Saving file....";
write.Close();
clientSock.Close();
MsgCurrent = "The file was received";
}
catch
{
MsgCurrent = "Error, the file was not received";
}
}
}
客户
class Client
{
public static string ipsendf;//added
public static string MsgCurrent = "Idle";
public static void SendFile(string fName)
{
try
{
IPAddress ip = IPAddress.Parse(ipsendf); //127.0.0.1 in "" as string
IPEndPoint end = new IPEndPoint(ip, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string path = "";
fName = fName.Replace("\\", "/");
while (fName.IndexOf("/") > -1)
{
path += fName.Substring(0, fName.IndexOf("/") + 1);
fName = fName.Substring(fName.IndexOf("/") + 1);
}
byte[] fNameByte = Encoding.ASCII.GetBytes(fName);
if (fNameByte.Length > 10 * 1024 * 1024) //count per byte
{
//MsgCurrent = "File is greater than 850 kb";
MsgCurrent = "File is greater than 10MB";
return;
}
MsgCurrent = "Buffering...";
byte[] fileData = File.ReadAllBytes(path + fName);
byte[] clientData = new byte[4 + fNameByte.Length + fileData.Length];
byte[] fNameLen = BitConverter.GetBytes(fNameByte.Length);
fNameLen.CopyTo(clientData, 0);
fNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fNameByte.Length);
MsgCurrent = "Connecting to server ...";
sock.Connect(end);
MsgCurrent = "File sending ...";
sock.Send(clientData);
MsgCurrent = "Disconnecting...";
sock.Close();
MsgCurrent = "The file was sent ..";
}
catch (Exception ex)
{
//do nothing
}
}
}
【问题讨论】:
标签: c# visual-studio file tcp ip