예제 #1
0
        static private void sendFile(object info)
        {
            Dictionary <string, object> callerInfo = (Dictionary <string, object>)info;
            //wait for server to acknowledge file with its properties
            ClientMainWindow caller = (ClientMainWindow)callerInfo["caller"];

            Byte[] buffer = new byte[64];
            int    rec;

            try
            {
                rec = client.Receive(buffer); //thread waits here!
            }
            catch
            {
                caller.disconnected();
                return;
            }
            if (rec <= 0)
            {
                caller.disconnected();
                return;
            }
            string serverResponse = Encoding.Default.GetString(buffer);

            if (serverResponse.Contains("$SENDFILE#"))
            {
                string fileName = (string)callerInfo["fileName"];
                //start to send the actual file
                client.SendFile(fileName);
                waitUploading(callerInfo);
            }
        }
예제 #2
0
 public void SendFile(string path)
 {
     byte[] fileDetail = fileManager.GetDetailAboutFile(path);
     clientSocket.Send(Encoding.UTF8.GetBytes("1"));
     clientSocket.Send(fileDetail);
     clientSocket.SendFile(path);
 }
예제 #3
0
        private static XDocument TalkOutIn(string requestPath, IPAddress serverIP)
        {
            XDocument resXml = null;

            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                IPEndPoint epThere = new IPEndPoint(serverIP, port);
                try
                {
                    IAsyncResult result  = s.BeginConnect(epThere, null, null);
                    bool         success = result.AsyncWaitHandle.WaitOne(3000, true);

                    if (s.Connected)
                    {
                        s.SendFile(requestPath);
                        resXml = UR.ReceiveXML(s);
                        s.Shutdown(SocketShutdown.Both);
                        s.EndConnect(result);
                    }
                    else
                    {
                        throw new ApplicationException("Failed to connect server.");
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("Can`t connect.\n" + e.Message);
                    if (s.Connected)
                    {
                        s.Shutdown(SocketShutdown.Both);
                    }
                }
            }
            return(resXml);
        }
예제 #4
0
        private void button4_Click(object sender, EventArgs e)//Перенести файл на сервер
        {
            if (on == false)
            {
                return;
            }
            Stream         myStream        = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();//Диалоговое окно для выбора файла

            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";


            if (openFileDialog1.ShowDialog() == DialogResult.OK)//Открытие окна
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)//Если выбрали файл
                    {
                        message = directory + '\\' + Path.GetFileName(openFileDialog1.FileName) + "?blink";
                        data    = Encoding.UTF8.GetBytes(message);
                        Connect();
                        //Отправляем данные через сокет
                        sent = client.Send(data);
                        Connect();
                        message = "";
                        data    = new byte[4096];
                        recv    = client.Receive(data);
                        message = Encoding.UTF8.GetString(data, 0, recv);

                        if (message == "Go")//сигнал для переноса
                        {
                            using (myStream)
                            {
                                client.SendFile(@"" + openFileDialog1.FileName);
                            }
                        }
                        clientClose();          //обрываем соединение
                        button1.PerformClick(); //переподключаемся
                        MessageBox.Show("Файл " + Path.GetFileName(openFileDialog1.FileName) + " перенесен ");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
        private static void receiveCallback(IAsyncResult result)
        {
            Socket socket = null;

            try
            {
                socket = (Socket)result.AsyncState;
                if (socket.Connected)
                {
                    int received = socket.EndReceive(result);
                    if (received > 0)
                    {
                        byte[] data = new byte[received];
                        Buffer.BlockCopy(buffer, 0, data, 0, data.Length);

                        string clientAddress = (socket.RemoteEndPoint as IPEndPoint).Address.ToString();
                        string clientData    = Encoding.UTF8.GetString(data);

                        if (File.Exists(clientData))
                        {
                            //@TODO check if the hash is valid befor send the file
                            socket.SendFile(clientData);
                        }
                        else
                        {
                            socket.Send(Encoding.ASCII.GetBytes("Error 404 file not found."));
                        }

                        receiveAttempt = 0;                                                                                          //reset receive attempt
                        socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket); //repeat beginReceive
                    }
                    else if (receiveAttempt < MAX_RECEIVE_ATTEMPT)
                    {
                        ++receiveAttempt;
                        socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket); //repeat beginReceive
                    }
                    else
                    {
                        Console.WriteLine("receiveCallback fails!"); //
                        receiveAttempt = 0;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("receiveCallback fails with exception! " + e.ToString());
            }
        }
예제 #6
0
        static void Main(string[] args)
        {
            byte[] bytes = new byte[1024];
            try
            {
                IPEndPoint ClientIPEP   = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
                Socket     ClientSender = new Socket(AddressFamily.InterNetwork,
                                                     SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    ClientSender.Connect(ClientIPEP);
                    Console.WriteLine("Socket connected to {0}", ClientSender.RemoteEndPoint.ToString());

                    string filename = "write location of asd.txt in debug/bin folder";

                    ClientSender.SendFile(filename);

                    byte [] msg       = Encoding.ASCII.GetBytes("This is a test <stop>");
                    int     bytesSent = ClientSender.Send(msg);

                    int bytesRec = ClientSender.Receive(bytes);
                    Console.WriteLine("Echoed test  = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
                    ClientSender.Shutdown(SocketShutdown.Both);
                    ClientSender.Close();
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("Argument Null Exception: {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("Socket Exception: {0}", se.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected Exception: {0}", e.ToString());
                }
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
예제 #7
0
        public void Start()
        {
            while (true)
            {
                IPAddress  ipAddress = new IPAddress(ServerIPAddress);
                IPEndPoint remoteEP  = new IPEndPoint(ipAddress, 12345);
                // Create a TCP/IP  socket.
                Socket sender = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    while (!connected)
                    {
                        try
                        {
                            // Connect the socket to the remote endpoint. Catch any errors.
                            sender.Connect(remoteEP);
                            connected = true;
                        }
                        catch (SocketException)
                        {
                            System.Console.WriteLine("Unable to connect to server. Retrying...");
                        }
                    }
                    Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());

                    XMLHandler.SavetoXml(SensorData);

                    sender.SendFile("measurement.xml");

                    Console.WriteLine("SENT");
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    Thread.Sleep(TimeInterval);
                    connected = false;
                }
            }
        }
예제 #8
0
        private async void UploadTask()
        {
            //Wait for a free space
            while (_isUploading)
            {
                Thread.Sleep(1000);
            }

            //Start uploading
            _isUploading = true;

            //Try to upload, and catch if it's not successfull.
            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    try
                    {
                        await socket.ConnectAsync(_endPoint.Address.ToString(), Data.UPLOAD_PORT);

                        // Send Length (Int64)
                        socket.SendFile(_filename);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Client Upload");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Client Upload Using");
            }

            //Upload's end
            _isUploading = false;
        }
예제 #9
0
 private static void sendOrderConfirmation(Socket s, string fName)
 {
     Console.WriteLine("\nClient sending 855 Confirmation to Server");
     s.SendFile(fName);
     Console.WriteLine("\t*Client has set 855 Confirmation to Server");
 }