学习型 ASP/PHP/ASP.NET 主机 30元/年全能 ASP/PHP/ASP.NET 主机,支持月付专业 MSSQL 数据库空间,支持月付专业 MySQL 数据库空间,支持月付
发新话题
打印

一个简单的基于tcp的client/server程序遇到问题

一个简单的基于tcp的client/server程序遇到问题

小第做一套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&lt;=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>

期待回答!!!不胜感激!

TOP

知道了一点,IP那里原来要添自己的真实IP,但是又有新问题了!!!

在c#中怎么可以动态获得自己的IP,假如多网卡又如何啊?

版主,求助!!!!!

TOP

以下是引用YuM在2004-06-25 21:11:13的发言:

版主,求助!!!!!

斑竹向广大的人民求助!!!!!!!!!

(斑竹是个站在门口的家伙,呵呵)

还请各位多多帮忙!

不雨花尤落 无风絮自飞

TOP

发新话题