public void Start(int listenPort) { ListenPort = listenPort; ipEndPoint = new IPEndPoint(ipAddr, ListenPort); listenSoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenSoc.Bind(ipEndPoint); listenSoc.Listen(10); listen = true; byte[] bytePath; int bytes = 0; int packageSize = 0; const int _BUFFERSIZE = 8192; while (true) { //Thread t = new Thread(delegate() //{ //}); try { handler = listenSoc.Accept(); } catch (Exception e) { if (listen) { throw e; } else { break; } } Invoke(new Action(() => { ConsoleWrite(handler.RemoteEndPoint.ToString() + " connected"); })); handler.Send(GetSendFileListPackage(filesList)); using (MemoryStream memStream = new MemoryStream()) { byte[] buffer = new byte[_BUFFERSIZE]; do { int received = handler.Receive(buffer); memStream.Write(buffer, 0, received); bytes += received; if (bytes >= 2049 && packageSize == 0) { packageSize = GetPackageSize(memStream.ToArray()); } }while (bytes < packageSize); packageSize = 0; bytes = 0; bytePath = memStream.ToArray(); if (bytePath.Length == 0) { continue; } } if (IsManyFiles(bytePath)) { string[] paths = GetReceivePaths(bytePath); NetFiles files = new NetFiles(); foreach (string path in paths) { using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] byteFile = new byte[stream.Length]; int length = stream.Read(byteFile, 0, byteFile.Length); NetFile file = new NetFile(); file.FileName = Path.GetFileName(stream.Name); file.Data = byteFile; files.Add(file); } } byte[] fullPackage = GetSendFilePackage(files.ToArray()); handler.Send(fullPackage); Invoke(new Action(() => { ConsoleWrite(string.Format("Отправлено {0} байт", fullPackage.Length)); })); } else { string path = GetReceivePath(bytePath); NetFile file = new NetFile(); using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] byteFile = new byte[stream.Length]; int length = stream.Read(byteFile, 0, byteFile.Length); file.FileName = Path.GetFileName(stream.Name); file.Data = byteFile; } byte[] fullPackage = GetSendFilePackage(file.ToArray()); handler.Send(fullPackage); Invoke(new Action(() => { ConsoleWrite(string.Format("Отправлено {0} байт", fullPackage.Length)); })); } } }