1. /**********TcpListener和TcpClient研究********** 
  2.  * 要点一:TcpListener起动后,如果有客户请求,就会建立一个TcpClient连接. 
  3.  * 要点二:通过TcpClient取得NetworkStream对象 
  4.  * 要点三:通过NetworkStream的Write和Read方法向连接的另一端发或接收数据 
  5.  * 要点四:传输的数据只能是字符流,需要编码. 
  6. **********************************************/  
  7. using System;  
  8. using System.Collections.Generic;  
  9. using System.ComponentModel;  
  10. using System.Data;  
  11. using System.Drawing;  
  12. using System.Text;  
  13. using System.Windows.Forms;  
  14.   
  15. using System.Net;  
  16. using System.Net.Sockets;  
  17. using System.Threading;  
  18.   
  19. namespace WinNet  
  20. {  
  21.     public partial class ServerFrm : Form  
  22.     {  
  23.         private Thread processor;  
  24.         private TcpListener tcpListener;  
  25.         string clientStr;  
  26.         public ServerFrm()  
  27.         {  
  28.             InitializeComponent();  
  29.         }  
  30.   
  31.         private void ServerFrm_Load(object sender, EventArgs e)  
  32.         {  
  33.             //需要在新的线程里监听客户端  
  34.             processor = new Thread(new ThreadStart(StartListening));  
  35.             processor.Start();  
  36.         }  
  37.         private void StartListening()  
  38.         {  
  39.             //创建一个监听对象  
  40.             tcpListener = new TcpListener(IPAddress.Any, 8888);  
  41.             tcpListener.Start();  
  42.             //循环监听  
  43.             while (true)  
  44.             {  
  45.                 try  
  46.                 {  
  47.                     //取得客户端的连接  
  48.                     TcpClient tcpClient = tcpListener.AcceptTcpClient();  
  49.                     //取得客户端发过来的字节流  
  50.                     NetworkStream clientStream = tcpClient.GetStream();  
  51.                     //把字节流读入字节数组  
  52.                     byte[] buffer = new byte[10];  
  53.                     clientStream.Read(buffer, 0, 10);  
  54.                     //不可以在此直接设置this.Text,线程问题.  
  55.                     clientStr= System.Text.Encoding.ASCII.GetString(buffer);  
  56.                     //向客户端发送数据  
  57.                     buffer = System.Text.Encoding.ASCII.GetBytes(“helloclint”.ToCharArray());  
  58.                     clientStream.Write(buffer, 0, 10);  
  59.                     //把字节流转化为字符串  
  60.                     this.Text = clientStr;  
  61.   
  62.                     tcpClient.Close();  
  63.                     clientStream.Close();  
  64.                 }  
  65.                 catch  
  66.                 {  
  67.                 }  
  68.             }  
  69.         }  
  70.     }  
  71. }