用C#實現基於TCP協議的網路通訊(1)
Visual C#.Net網路程式開發-Tcp篇(2)
Pushing Data to a Silverlight Client with Sockets: Part I
下面的執行個體實現了簡單的網路通訊-雙機互連,針對用戶端和服務端分別編製了應用程式。用戶端建立到服務端的串連,向遠程主機發送串連請求串連訊號,並發送交談內容;遠程主機端接收來自客戶的串連,向用戶端發回確認串連的訊號,同時接收並顯示用戶端的交談內容。在這個基礎上,發揮你的創造力,你完全可以開發出一個基於程式語言(C#)級的聊天室!
用戶端主要原始碼:
public void SendMeg()//發送資訊
{
try
{
int port=Int32.Parse(textBox3.Text.ToString());//遠程主機連接埠
try
{
tcpClient=new TcpClient(textBox1.Text,port);//建立TcpClient對象執行個體 }
catch(Exception le)
{
MessageBox.Show("TcpClient Error:"+le.Message);
}
string strDateLine=DateTime.Now.ToShortDateString()+" "+DateTime.Now.ToLongTimeString();//得到發送時用戶端時間
netStream=tcpClient.GetStream();//得到網路流
sw=new StreamWriter(netStream);//建立TextWriter,向流中寫字元
string words=textBox4.Text;//待發送的話
string content=strDateLine+words;//待發送內容
sw.Write(content);//寫入流
sw.Close();//關閉流寫入器
netStream.Close();//關閉網路流
tcpClient.Close();//關閉用戶端串連
}
catch(Exception ex)
{
MessageBox.Show("Sending Message Failed!"+ex.Message);
}
textBox4.Text="";//清空
}
伺服器端主要原始碼:
public void StartListen()//偵聽特定連接埠的使用者請求
{
//ReceiveMeg();
isLinked=false; //串連標誌
try
{
int port=Int32.Parse(textBox1.Text.ToString());//本地待偵聽連接埠
serverListener=new TcpListener(port);//建立TcpListener對象執行個體
serverListener.Start(); //啟動偵聽
}
catch(Exception ex)
{
MessageBox.Show("Can't Start Server"+ex.Message);
return;
}
isLinked=true;
while(true)//進入無限迴圈等待使用者端串連
{
try
{
tcpClient=serverListener.AcceptTcpClient();//建立用戶端連線物件
netStream=tcpClient.GetStream();//得到網路流
sr=new StreamReader(netStream);//流讀寫器
}
catch(Exception re)
{
MessageBox.Show(re.Message);
}
string buffer="";
string received="";
received+=sr.ReadLine();//讀流中一行
while(received.Length!=0)
{
buffer+=received;
buffer+="\r\n";
//received="";
received=sr.ReadLine();
}
listBox1.Items.Add(buffer);//顯示
//關閉
sr.Close();
netStream.Close();
tcpClient.Close();
}
}