刚刚学习了socket,照着例子自己又敲了一遍代码,过程中突然想到一个功能,可不可以在服务端没有启动之前,客户端就去一直Connected,知道服务端启动后连接到服务端。但是我尝试去做的时候,先启动客户端(我把连接功能写到了窗体加载时间里了。)Connect就会引发SocketException异常,提示说“由于目标计算机积极拒绝,无法连接。 192.168.55.22:9988”下面贴客户端部分代码
try
{
socketConnection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipa = IPAddress.Parse(txtIP.Text.Trim());
endpoint = new IPEndPoint(ipa, int.Parse(txtPort.Text.Trim()));
socketConnection.Connect(endpoint);
threadWatch = new Thread(connectionRec);
threadWatch.IsBackground = true;
threadWatch.Start();
}
catch (SocketException ex)
{
do
{
socketConnection.Connect(endpoint);
} while (socketConnection.Connected == false);
threadWatch = new Thread(connectionRec);
threadWatch.IsBackground = true;
threadWatch.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex + "");
}
try
{
socketConnection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipa = IPAddress.Parse(txtIP.Text.Trim());
endpoint = new IPEndPoint(ipa, int.Parse(txtPort.Text.Trim()));
socketConnection.Connect(endpoint);
threadWatch = new Thread(connectionRec);
threadWatch.IsBackground = true;
threadWatch.Start();
}
catch (SocketException ex)
{
do
{
socketConnection.Connect(endpoint);
} while (socketConnection.Connected == false);
threadWatch = new Thread(connectionRec);
threadWatch.IsBackground = true;
threadWatch.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex + "");
}
//可以参考一下这个,有一些异常提示你可以删除掉,就不会弹对话框。
public void link()
{
IPAddress ipRemote;
string ip = ConfigurationManager.AppSettings["MainMachine"].ToString();
string ipport = ConfigurationManager.AppSettings["MainMachinePort"].ToString();
try
{
ipRemote = IPAddress.Parse(ip);
}
catch //判断给定的IP地址的合法性
{
MessageBox.Show(string.Format("输入的IP地址{0}不合法!", ip), "错误提示");
return;
}
IPHostEntry ipHost;
try//判断IP地址对应主机是否在线
{
ipHost = Dns.GetHostEntry(ip);
}
catch
{
MessageBox.Show(string.Format("远程主机{0}不在线!", ip), "错误提示!");
return;
}
string sHostName = ipHost.HostName;
try
{
tcpClient = new TcpClient(sHostName, int.Parse(ipport));//对远程主机的8000端口提出TCP连接申请
nsStream = tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据流
swWriter = new StreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例
tcpConnect = true;
label1.Text = "已经连接!";
}
catch
{
MessageBox.Show(string.Format("无法和远程主机{0}:端口{1}建立连接!", ip, ipport), "错误提示!");
return;
}
}