一个在本地侦听。一个去连接对方。

解决方案 »

  1.   

    两方面必须协同操作,一台打开端口开始侦听,最好是单独开一个线程,另一台过来请求
      

  2.   

    你们所说是不是这样
    private void Listen()
    {
    try
    {
    tcpl = new TcpListener(5656);
    tcpl.Start();
    statusBar1.Text = "正在监听..."; while(listenerRun)
    {
    Socket s = tcpl.AcceptSocket();
    Byte[] stream = new Byte[80];
    int i=s.Receive(stream) ;
    string message = System.Text.Encoding.UTF8.GetString(stream);
    richTextBox1.AppendText(message);
    }
    }
    catch(System.Security.SecurityException)
    {
    MessageBox.Show("防火墙安全错误!","错误",
    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
    catch(Exception)
    {
    statusBar1.Text = "已停止监听!";
    }
    }private void Send()
    {
    try
    {
    string msg = "<"+textBox3.Text+">"+textBox2.Text;
    TcpClient tcpc = new TcpClient(textBox1.Text, 5656);
    NetworkStream tcpStream = tcpc.GetStream(); StreamWriter reqStreamW = new StreamWriter(tcpStream);
    reqStreamW.Write(msg);
    reqStreamW.Flush();
    tcpStream.Close();
    tcpc.Close();
    richTextBox1.AppendText(msg);
    textBox2.Clear();
    }
    catch(Exception)
    {
    statusBar1.Text = "目标计算机拒绝连接请求!";
    }
    }
    但是如果中间有NAT转换(在网上看到的 http://www.ppcn.net/show.aspx?id=1306&cid=2 )
    比如A使用端口[P1]连接B端口[P2]然后B又连接A端口[P1]这时A怎么知道要侦听那个端口侦听