在上篇裡介紹了Socket的基本編程,這次來看看.net封裝的基於TCP協議的發送和接收端
TCP協議的接收端
using System.Net.Sockets ; //使用到TcpListen類
using System.Threading ; //使用到線程
using System.IO ; //使用到StreamReader類
int port = 8000; //定義偵聽端口號
private Thread thThreadRead; //創建線程,用以偵聽端口號,接收信息
private TcpListener tlTcpListen; //偵聽端口號
private bool blistener = true; //設定標示位,判斷偵聽狀態
private NetworkStream nsStream; //創建接收的基本數據流
private StreamReader srRead;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ListBox listBox1; //從網絡基礎數據流中讀取數據
private TcpClient tcClient ;
private void Listen ( )
{
try
{
tlTcpListen = new TcpListener ( port ) ; //以8000端口號來初始化TcpListener實例
tlTcpListen.Start ( ) ; //開始監聽
statusBar1.Text = "正在監聽..." ;
tcClient = tlTcpListen.AcceptTcpClient ( ) ; //通過TCP連接請求
nsStream = tcClient.GetStream ( ) ; //獲取用以發送、接收數據的網絡基礎數據流
srRead=new StreamReader(nsStream);//以得到的網絡基礎數據流來初始化StreamReader實例
statusBar1.Text = "已經連接!";
while( blistener ) //循環偵聽
{
string sMessage = srRead.ReadLine();//從網絡基礎數據流中讀取一行數據
if ( sMessage == "STOP" ) //判斷是否為斷開TCP連接控制碼
{
tlTcpListen.Stop(); //關閉偵聽
nsStream.Close(); //釋放資源
srRead.Close();
statusBar1.Text = "連接已經關閉!" ;
thThreadRead.Abort(); //中止線程
return;
}
string sTime = DateTime.Now.ToShortTimeString ( ) ; //獲取接收數據時的時間
listBox1.Items.Add ( sTime + " " + sMessage ) ;
}
}
catch ( System.Security.SecurityException )
{
MessageBox.Show ( "偵聽失敗!" , "錯誤" ) ;
}
}
//開始監聽
private void button1_Click(object sender, System.EventArgs e)
{
thThreadRead = new Thread ( new ThreadStart ( Listen ) );
thThreadRead.Start();//啟動線程
button1.Enabled=false;
}
// 清理所有正在使用的資源。
protected override void Dispose( bool disposing )
{
try
{
tlTcpListen.Stop(); //關閉偵聽
nsStream.Close();
srRead.Close();//釋放資源
thThreadRead.Abort();//中止線程
}
catch{}
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
TCP協議的發送端
using System.Net.Sockets; //使用到TcpListen類
using System.Threading; //使用到線程
using System.IO; //使用到StreamWriter類
using System.Net; //使用IPAddress類


