我已經創建了一個使用TCP/IP套接字文件傳輸communication.Now我想添加一個功能,檢查TCP/IP coonection就具體的遠程服務器的應用程序端口號(無論是否可用於轉移)。所以,請有任何人幫助我。提前感謝。如何使用C#(socket通信)來檢查TCP/IP端口可用性
如果(string.IsNullOrEmpty(txtIP.Text)) 回報;
如果(string.IsNullOrEmpty( 「8001」)) 回報;
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)
私人無效telnetSocketAsyncEventArgs_Completed(對象發件人,的SocketAsyncEventArgs E) { 嘗試 { 如果(e.SocketError == SocketError.Success) { 如果(e.LastOperation == SocketAsyncOperation.Connect) { MessageBox.Show( 「服務正在運行」,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);
}
}
}
要知道您是否能夠成功完成轉移,唯一的方法就是實際嘗試轉移。其他任何事情都會受到競爭條件的影響,例如網絡可能發生變化,服務器可能失敗等等。 –