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

來源:互聯網
上載者:User
綜合運用上面的知識,下面的實例實現了簡單的網路通訊-雙機互連,針對用戶端和服務端分別編制了應用程式。用戶端創建到服務端的連接,向遠端主機發送連接請求連接信號,並發送交談內容;遠端主機端接收來自用戶的連接,向用戶端發回確認連接的信號,同時接收並顯示用戶端的交談內容。在這個基礎上,發揮你的創造力,你完全可以開發出一個基於程式語言(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.