0

I have created a application for transferring files using TCP/IP socket communication.Now i want to add a feature that checks TCP/IP coonection to remote server on specific port number(whether its available or not for transfer).So,Kindly any one help me in this.Thanks in advance.

if (string.IsNullOrEmpty(txtIP.Text)) return;

if (string.IsNullOrEmpty("8001")) return;

                int port;
                hostAddress = Dns.GetHostEntry(txtIP.Text).AddressList[0];
                int.TryParse("8001", out port);
                StateObject state = new StateObject();
                if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                    state.workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                else if (hostAddress.AddressFamily == AddressFamily.InterNetworkV6)
                    state.workSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

                SocketAsyncEventArgs telnetSocketAsyncEventArgs = new SocketAsyncEventArgs();
                telnetSocketAsyncEventArgs.RemoteEndPoint = new IPEndPoint(hostAddress, port);
                telnetSocketAsyncEventArgs.Completed += new
                    EventHandler<SocketAsyncEventArgs>(telnetSocketAsyncEventArgs_Completed);

                state.workSocket.ConnectAsync(telnetSocketAsyncEventArgs)

private void telnetSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e) { try { if (e.SocketError == SocketError.Success) { if (e.LastOperation == SocketAsyncOperation.Connect) { MessageBox.Show("Service Is Running", hostAddress.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);

                        ////send file if connection is established.
                    Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    byte[] fileName = Encoding.UTF8.GetBytes(m_fName); //file name
                    byte[] fileData = File.ReadAllBytes(txtFilePath.Text); //file
                    byte[] fileNameLen = BitConverter.GetBytes(fileName.Length); //lenght of file name
                    m_clientData = new byte[fileNameLen.Length + fileName.Length + fileData.Length];

                    fileNameLen.CopyTo(m_clientData, 0);
                    fileName.CopyTo(m_clientData, fileNameLen.Length);
                    fileData.CopyTo(m_clientData, fileNameLen.Length + fileName.Length);

                    //Code for Progress bar
                    lblmsg.Text = "";
                    double divider;
                    int extra;
                    fileProgress.Value = 0;
                    divider = (double)m_clientData.Length / 1024;
                    divider = Math.Ceiling(divider);
                    fileProgress.Maximum = m_clientData.Length;
                    int packet = 0;
                    for (int i = 0; i < divider; i++)
                    {
                        if (i == (divider - 1))
                        {
                            extra = (m_clientData.Length) - (i * 1024);
                            clientSock.Send(m_clientData, packet, extra, SocketFlags.None);
                        }
                        else
                        {
                            clientSock.Send(m_clientData, packet, 1024, SocketFlags.None);
                            packet = packet + 1024;
                            fileProgress.Value += 1024;
                        }
                    }
                    clientSock.Close();
                    fileProgress.Value = fileProgress.Maximum;
                    lblSender.Text = "File upload is completed.";
                    clientSocket.Disconnect(true);
                   // }

                }
            }
            else
            {
                bPortAvailble = false;
                MessageBox.Show("Service Is not Running", e.SocketError.ToString(),
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        catch (SocketException ex)
        {
            MessageBox.Show(ex.Message, "Service Is not Running",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }


}
user3748116
  • 11
  • 1
  • 6
  • The only way to know whether you'll be able to successfully complete a transfer is to actually attempt the transfer. Anything else is subject to race conditions, such as the fact that the network can change, servers can fail, etc. – Damien_The_Unbeliever Jun 17 '14 at 12:30

1 Answers1

0

You can try establishing a connection using TcpClient and catching an exception : TcpClient.

In your case, where you're using the Socket class, look here: Socket class. The Send method should be failing if you don't Connect first, quoting from here:

If you are using a connectionless protocol, you must call Connect before calling this method, or Send will throw a SocketException.

So first use Connect, and catch if it throws a SocketExcpetion.

kobigurk
  • 731
  • 5
  • 14
  • It's exactly what you asked :-) Although, if you'd give more information about how the file transfer initiation works, we might be able to combine them. – kobigurk Jun 17 '14 at 10:56
  • Hi kobigurk,i have attached the code for file transfer that is in send button click.In this i want to check the availability before sending. – user3748116 Jun 17 '14 at 11:05
  • Hi kobigurk,i tried in a different manner.In button click i am checking connectivity using "telnetSocketAsyncEventArgs" event.That event will be rised either if connection succeeds or fails.So if it is success i am sending the data.But the problem i am facing here is its throwing exception as " "Cross-thread operation not valid: Control 'fileProgress' accessed from a thread other than the thread it was created on." at the line - "fileProgress.Maximum = m_clientData.Length;" – user3748116 Jun 17 '14 at 12:03
  • that's because `fileProgress` is a UI control created on the UI thread. In order to access it, you must use `Invoke`. Read about it here: http://stackoverflow.com/questions/1423446/thread-control-invoke – kobigurk Jun 17 '14 at 13:21