小第做一套client/server的程序:
server开启,监听localhost的4321端口,client启动后填写主机IP进行连接,之后进行输入,在服务端显示
问题是:只有IP打127.0.0.1或者localhost的时候才可以成功连接,如果打机器的真实IP连接不了,高手可以告诉我为什么吗??
两个文件的代码如下:
net_server.cs
复制内容到剪贴板代码:
</P>
<P>using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
//using System.Threading;</P>
<P>public class net_server
{
public static void Main()
{
try
{
Int32 port = 4321;
IPAddress localAddr = Dns.Resolve("localhost").AddressList[0];</P>
<P> TcpListener server = new TcpListener(localAddr, port);</P>
<P> server.Start();
Byte[] bytes = new Byte[256];
String data = null;</P>
<P> while(true)
{
Console.WriteLine("服务程序正在监听。。。");</P>
<P> TcpClient client = server.AcceptTcpClient();
Console.WriteLine("成功建立连接。。。");</P>
<P> data = null;</P>
<P> NetworkStream stream = client.GetStream();</P>
<P> Int32 i;</P>
<P> while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(String.Format("Received: {0}", data));
}
client.Close();
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}</P>
<P>
net_client.cs
复制内容到剪贴板代码:
</P>
<P>using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
//using System.Threading;</P>
<P>public class net_client
{
public static void Main(string[] args)
{
string host;
Int32 port = 4321;</P>
<P> if(args.Length<=0)
{
Console.Write("请输入主机IP地址:");
host=Console.ReadLine();
}
else
{
host=args[0];
}
</P>
<P> //IPAddress server = IPAddress.Parse(host);
//IPEndPoint ipEP=new IPEndPoint(server,port);
try
{
TcpClient client = new TcpClient(host,port);
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[256];
string senddata;
while(true)
{
senddata=Console.ReadLine();
data = System.Text.Encoding.ASCII.GetBytes(senddata);
stream.Write(data,0,data.Length);
}
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
catch (Exception e )
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
}</P>
<P>
期待回答!!!不胜感激!