C#完成簡略聊天法式的辦法。本站提示廣大學習愛好者:(C#完成簡略聊天法式的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成簡略聊天法式的辦法正文
本文實例講述了C#簡略聊天法式完成辦法。分享給年夜家供年夜家參考。詳細以下:
假設有辦事器端法式,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(); }
願望本文所述對年夜家的C#法式設計有所贊助。