假如有服務器端程序,ChatServer和客戶端程序ChatClient.實現客戶端向服務器端發送信息的簡單功能. 運行步驟, 1.先是服務器端start listen, 2.然後客戶端connect. 3.客戶端發送消息 只要服務器端start listen了,然後客戶端也connect了.這樣建立起連接後.接受發送信息就方便了,只要用writer,reader去操作NetworkStream 服務器ChatServer 創建一個WinForm頁面 引用命名空間: using System.Net.Sockets; using System.Net; using System.IO; using System.Threading; public class ChatServer { private int port = 54321; //端口號 private IPAddress ip = IPAddress.Parse("10.20.30.40"); //ip地址 private TcpListener tcpListener= null; private TcpClient tcpClient = null; private NetworkStream networkStream = null; private BinaryReader reader; //private BinaryWriter writer; private string getInfo = string.empty; //開始監聽 private void btnStartListen_Click(object sender, EventArgs e) { tcpListener= new TcpListener( ip , port); tcpListener.Start(); //開始監聽 Thread acceptClientMsgThread= new Thread(AcceptClientMsg); //運行一個線程去處理客戶端發來的信息 acceptClientMsgThread.Start(); } //處理客戶端發來的信息 private void AcceptClientMsg() { tcpClient = tcpListener.AcceptTcpClient(); if( tcpClient != null) { networkStream = tcpClient.GetStream(); reader = new BinaryReader( networkStream); while (true){ getInfo += reader.ReadString(); //讀取客戶端發來的信息 } } } //假如還要顯示信息的話,可以整個顯示按鈕(當然最好的辦法是用些線程) //然後點擊button後讓信息顯示出來txtShowClientMsg.Text = getInfo; //如果服務器端想再給客戶端發信息,就可以整個發送按鈕.然後添加如下代碼 //string sendMsg = txtSendMsge.Text; //writer = new BinaryWriter( networkStream); //writer.write( sendMsg); } 客戶端ChatClient using System.Net.Sockets; using System.Net; using System.IO; using System.Threading; public class ChatClient { private int port = 54321; private IPAddress ip = IPAddress.Parse("10.20.30.40"); private TcpClient tcpClient = null; private NetworkStream networkStream = null; //private BinaryReader reader; private BinaryWriter writer; //連接server private void btnStartConnect_Click(object sender, EventArgs e) { tcpClient = new TcpClient(); tcpClient.Connect( ip, port); networkStream = tcpClient.GetStream(); } //發送信息 private void btnStartConnect_Click(object sender, EventArgs e) { string sendMsg = txtSendMsg.Text; writer = new BinaryWriter( networkStream); writer.Write( sendMsg); //發送信息 } //如果還要接受server的消息的話. //reader = new BinaryReader( networkStream); //string getInfo = reader.ReadString(); }