Visual C#.Net網路程式開發-Tcp篇(3)

來源:互聯網
上載者:User


用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();
}
}  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.