Мой сервер не получает файл.Может кто-то помочь мне, пожалуйста?Также я хочу узнать, как заставить сервер отправлять файл другому клиенту после получения файла от одного клиента
Client.cs
private void button1_Click(object sender, EventArgs e)
{
FileDialog fDg = new OpenFileDialog();
if (fDg.ShowDialog() == DialogResult.OK)
{
FTClientCode.SendFile(fDg.FileName);
}
}
class FTClientCode
{
public static void SendFile(string fileName)
{
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("host");
IPEndPoint ipEnd = new IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);string filePath = "";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)
{
return;
}
byte[] fileData = File.ReadAllBytes(filePath + fileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
clientSock.Connect(ipEnd);
clientSock.Send(clientData);
clientSock.Close();
}
catch (Exception ex)
{
}
}
}
Server.cs
public static string receivedPath = @"M:\Music\";
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
FTServerCode obj = new FTServerCode();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
obj.StartServer();
}
class FTServerCode
{
IPEndPoint ipEnd;
Socket sock;
public FTServerCode()
{
ipEnd = new IPEndPoint(IPAddress.Any, 5656);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
public void StartServer()
{
try
{
sock.Listen(100);
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024 * 5000];
int receivedBytesLen = clientSock.Receive(clientData);
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + "/" + fileName,FileMode.Append));
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
bWrite.Close();
clientSock.Close();
}
catch (Exception ex)
{
}
}