ServerFrm.cs/**********TcpListener和TcpClient研究********** * 要点一:TcpListener起动后,如果有客户请求,就会建立一个TcpClient连接. * 要点二:通过TcpClient取得NetworkStream对象 * 要点三:通过NetworkStream的Write和Read方法向连接的另一端发或接收数据 * 要点四:传输的数据只能是字符流,需要编码. **********************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace WinNet { public partial class ServerFrm : Form { private Thread processor; private TcpListener tcpListener; string clientStr; public ServerFrm() { InitializeComponent(); } private void ServerFrm_Load(object sender, EventArgs e) { //需要在新的线程里监听客户端 processor = new Thread(new ThreadStart(StartListening)); processor.Start(); } private void StartListening() { //创建一个监听对象 tcpListener = new TcpListener(IPAddress.Any, 8888); tcpListener.Start(); //循环监听 while (true) { try { //取得客户端的连接 TcpClient tcpClient = tcpListener.AcceptTcpClient(); //取得客户端发过来的字节流 NetworkStream clientStream = tcpClient.GetStream(); //把字节流读入字节数组 byte[] buffer = new byte[10]; clientStream.Read(buffer, 0, 10); //不可以在此直接设置this.Text,线程问题. clientStr= System.Text.Encoding.ASCII.GetString(buffer); //向客户端发送数据 buffer = System.Text.Encoding.ASCII.GetBytes("helloclint".ToCharArray()); clientStream.Write(buffer, 0, 10); //把字节流转化为字符串 this.Text = clientStr; tcpClient.Close(); clientStream.Close(); } catch { } } } } } ClientFrm.csusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace WinNet { public partial class ClientFrm : Form { public ClientFrm() { InitializeComponent(); } private void ClientFrm_Load(object sender, EventArgs e) { //这就是服务器与客户端的一条通讯线路 TcpClient tcpClient = new TcpClient(); //得到服务器端IP,然后建立一个连接 IPHostEntry host = Dns.GetHostEntry("127.0.0.1"); tcpClient.Connect(host.AddressList[0], 8888); //取得数据流 NetworkStream clientStream = tcpClient.GetStream(); //只能向服务器发送字节流,所以要编码 byte[] response = new byte[10]; response = System.Text.Encoding.ASCII.GetBytes("helloserve".ToCharArray()); //通过Write方法把客户端数据发向服务器 clientStream.Write(response, 0, 10); //通过Read方法读取服务器端发过来的数据 clientStream.Read(response, 0, 10); this.Text = System.Text.Encoding.ASCII.GetString(response); tcpClient.Close(); clientStream.Close(); } } }