小第做一套client/server的程序:
server开启,监听localhost的4321端口,client启动后填写主机IP进行连接,之后进行输入,在服务端显示
问题是:只有IP打127.0.0.1或者localhost的时候才可以成功连接,如果打机器的真实IP连接不了,高手可以告诉我为什么吗?? 两个文件的代码如下:
net_server.cs
using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; //using System.Threading;
public class net_server { public static void Main() { try { Int32 port = 4321; IPAddress localAddr = Dns.Resolve(\"localhost\").AddressList[0];
TcpListener server = new TcpListener(localAddr, port);
server.Start(); Byte[] bytes = new Byte[256]; String data = null;
while(true) { Console.WriteLine(\"服务程序正在监听。。。\");
TcpClient client = server.AcceptTcpClient(); Console.WriteLine(\"成功建立连接。。。\");
data = null;
NetworkStream stream = client.GetStream();
Int32 i;
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(); } }
net_client.cs
using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; //using System.Threading;
public class net_client { public static void Main(string[] args) { string host; Int32 port = 4321;
if(args.Length<=0) { Console.Write(\"请输入主机IP地址:\"); host=Console.ReadLine(); } else { host=args[0]; }
//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(); } }
期待回答!!!不胜感激!