主题:有关socket的问题?
try
{
int port = 1003;
string host = "192.168.0.129";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
int _p = 1003;
c.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.102"),_p));//本机IP192.168.0.102
Console.WriteLine("Conneting...");
c.Connect(ipe);//连接到服务器
string sendStr = "hello!Thisisasockettest";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
Console.WriteLine("SendMessage");
c.Send(bs, bs.Length, 0);//发送测试信息
//c.SendTo(bs, ipe);
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
while (true)
{
bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("ClientGetMessage:{0}", recvStr);//显示服务器返回信息
}
c.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException:{0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException:{0}", e);
}
Console.WriteLine("PressEntertoExit");
Console.ReadLine();
}
//e.Message 为: "The requested address is not valid in its context"
{
int port = 1003;
string host = "192.168.0.129";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
int _p = 1003;
c.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.102"),_p));//本机IP192.168.0.102
Console.WriteLine("Conneting...");
c.Connect(ipe);//连接到服务器
string sendStr = "hello!Thisisasockettest";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
Console.WriteLine("SendMessage");
c.Send(bs, bs.Length, 0);//发送测试信息
//c.SendTo(bs, ipe);
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
while (true)
{
bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("ClientGetMessage:{0}", recvStr);//显示服务器返回信息
}
c.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException:{0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException:{0}", e);
}
Console.WriteLine("PressEntertoExit");
Console.ReadLine();
}
//e.Message 为: "The requested address is not valid in its context"