两台同时处于内网机器....如何建立..TCP连接? 我知道..通过服务器可以使两台处于内网的机器..进行"UDP打洞"连接! 可是TCP不一样....实现起来..很困难... 您给点思路吧....
应该是一样吧。那个UDP链接,是声明一个UDP监听对象
这个TCP 直接用TCp监听对象来不行吗?..
有办法看看这个
http://space.cnblogs.com/group/topic/13033/
客户端:
Code public class TcpTimeClient { private const int portNum = 13;//服务器端口,可以随意修改 private const string hostName = "127.0.0.1";//服务器地址,127.0.0.1指本机 [STAThread] static void Main(string[] args) { try { Console.Write("Try to connect to "+hostName+":"+portNum.ToString()+"\r\n"); TcpClient client = new TcpClient(hostName, portNum); NetworkStream ns = client.GetStream(); byte[] bytes = new byte[1024]; int bytesRead = ns.Read(bytes, 0, bytes.Length); Console.WriteLine(Encoding.ASCII.GetString(bytes,0,bytesRead)); client.Close(); Console.ReadLine();//由于是控制台程序,故为了清楚的看到结果,可以加上这句 } catch (Exception e) { Console.WriteLine(e.ToString()); } } }
Codeclass TimeServer { private const int portNum = 13; [STAThread] static void Main(string[] args) { bool done = false; TcpListener listener = new TcpListener(portNum); listener.Start(); while (!done) { Console.Write("Waiting for connection"); TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Connection accepted."); NetworkStream ns = client.GetStream(); byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString()); try { ns.Write(byteTime, 0, byteTime.Length); ns.Close(); client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } listener.Stop(); } }