.Net 4.5的写法
try
{
// TcpClient client = new TcpClient(textBox_ip.Text.Trim(), Convert.ToInt32(textBox_port.Text.Trim()));
// TcpClient client = new TcpClient(ip.Trim(), Convert.ToInt32(port.Trim()));
TcpClient client = new TcpClient();
// client.Connect(ip.Trim(), Convert.ToInt32(port.Trim()));
if(!client.ConnectAsync(ip.Trim(),Convert.ToInt32(port.Trim())).Wait(5000)) //设置5秒超时
{
recv_text_data = "SocketException Connect Error!";
}
if (client.Connected)
{
NetworkStream serverStream = client.GetStream();
var newmsg = new SerMessage();
var client = new TcpClient(); if (!client.ConnectAsync("remotehost", remotePort).Wait(1000)) { // connection failure }
4.5以前
var client = new TcpClient(); var result = client.BeginConnect("remotehost", this.Port, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1)); if (!success) { throw new Exception("Failed to connect."); } // we have connected client.EndConnect(result);