C#完成点对点聊天程序(核心代码)

//服务端
   TcpClient tc = null;
   TcpListener tl = null;
   private void button1_Click(object sender, System.EventArgs e)
   {
    tl = new TcpListener(IPAddress.Any,1234);
    tl.Start();
    this.label1.Text = "开始侦听!";
   }

   private void button2_Click(object sender, System.EventArgs e)
   {
    tc = tl.AcceptTcpClient();
    NetworkStream ns = tc.GetStream();
    StreamReader sr = new StreamReader(ns); //先从客户端读数据
    this.listBox1.Items.Add(sr.ReadLine());

    StreamWriter sw = new StreamWriter(ns); //再写数据
    sw.WriteLine(this.textBox2.Text);
    sw.Flush();

   }


//客户端
   private void button1_Click(object sender, System.EventArgs e)
   {   
    TcpClient tc = new TcpClient("127.0.0.1",1234);
    NetworkStream ns = tc.GetStream();     
    StreamWriter sw = new StreamWriter(ns);   //先写数据
    sw.WriteLine(this.textBox2.Text);
    sw.Flush();

    StreamReader sr = new StreamReader(ns); //再从服务端读数据
    this.listBox1.Items.Add(sr.ReadLine());
   }

 

摘自:http://hi.baidu.com/foible/blog/item/107d62d73d3472d9a144df06.html

你可能感兴趣的:(C#完成点对点聊天程序(核心代码))