异步Socket通讯,报错误“由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。”
小弟刚接触socket,就遇到了难题,异步Socket通讯,报错误“由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。”
代码是这么写的
服务器端
private void button1_Click(object sender, EventArgs e)
{
try
{
listener = new AsySocket("192.168.1.3", Int32.Parse("5555"));
listener.OnAccept += new AcceptEventHandler(listener_OnAccept);
listener.Listen(10);
this.button1.Enabled = false;
}
catch (Exception en)
{
MessageBox.Show(en.Message);
}
}
客户端
//客户端
private void button2_Click(object sender, EventArgs e)
{
try
{
socket = new AsySocket("localhost", 0);
socket.OnSended += new AsySocketEventHandler(socket_OnSended);
socket.OnSendTo += new AsySocketEventHandler(socket_OnSendTo);
socket.OnStreamDataAccept += new StreamDataAcceptHandler(socket_OnStreamDataAccept);
socket.OnStringDataAccept += new StringDataAcceptHandler(socket_OnStringDataAccept);
socket.OnClosed += new AsySocketClosedEventHandler(socket_OnClosed);
socket.LinkObject.Connect("192.168.1.3", 5555);
button1.Enabled = false;
socket.BeginAcceptData();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
而AsySocket的关键代码,我也贴出
public class AsySocket
{
/// <summary>
///
/// </summary>
/// <param name="LocalIP"></param>
/// <param name="LocalPort"></param>
public AsySocket(string LocalIP, int LocalPort)
{
mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
IPAddress ip = Dns.GetHostAddresses(LocalIP)[0];
IPEndPoint ipe = new IPEndPoint(ip, LocalPort);
mID = Guid.NewGuid().ToString();
mSocket.Bind(ipe);
}
catch (Exception e)
{
//ErrLog.RecordErr(e, ModuleName, "AsySocket", "");
}
}
以下是文字说明,
应该排除端口问题,测试机器上未开启windows防火墙,5555端口是可以telnet的,单机试验可以顺利通过(服务器端和客户端都是本机),而服务器端和客户端分别部署两个机器,客户端开始连接的时候就报错“由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。”,百思不得其解,还请高人指点
------解决方案--------------------
http://topic.csdn.net/u/20080623/08/4bbd2475-45f1-42e3-a613-16b094759ade.html?62697
------解决方案--------------------
AsySocket("localhost", 0);
------解决方案--------------------
设置连接超时