{
try
{
tlTcpListen = new TcpListener ( port ) ;
//以8000端口號來初始化TcpListener實(shí)例
tlTcpListen.Start ( ) ;
//開始監(jiān)聽網(wǎng)絡(luò)的連接請求
statusBar1.Text = "正在監(jiān)聽..." ;
stRead = tlTcpListen.AcceptSocket ( ) ;
//通過連接請求,并獲得接收數(shù)據(jù)時(shí)使用的Socket實(shí)例
EndPoint tempRemoteEP = stRead.RemoteEndPoint ;
IPEndPoint tempRemoteIP = ( IPEndPoint ) tempRemoteEP ;
//獲取請求的遠(yuǎn)程計(jì)算機(jī)名稱
IPHostEntry host = Dns.GetHostByAddress
( tempRemoteIP.Address ) ;
string sHostName = host.HostName ;
statusBar1.Text = "已經(jīng)連接!" ;
//循環(huán)偵聽
while ( blistener )
{
string sTime = DateTime.Now.ToShortTimeString ( ) ;
//獲取接收數(shù)據(jù)時(shí)的時(shí)間
Byte [ ] byRead =new Byte [ 80 ] ;
int iRead = stRead.ReceiveFrom
( byRead , ref tempRemoteEP ) ;
//獲得接收的字節(jié)數(shù)目
Byte [ ] byText = new Byte [ iRead ] ;
//并根據(jù)接收到的字節(jié)數(shù)目來定義字節(jié)數(shù)組
Array.Copy ( byRead , 0 , byText , 0 , iRead ) ;
string sTemp = System.Text.Encoding.Default.
GetString ( byText ) ;
//判斷是否為斷開連接控制碼
if ( sTemp.Trim ( ) == "STOP" )
{
stRead.Close ( ) ;
tlTcpListen.Stop ( ) ;
//關(guān)閉偵聽
statusBar1.Text = "連接已經(jīng)關(guān)閉!" ;
thThreadRead.Abort ( ) ;
//中止線程
return ;
}
else
listBox1.Items.Add ( sTime + " " + sTemp ) ;
} catch ( System.Security.SecurityException )
{
MessageBox.Show ( "偵聽失??!" , "錯誤" ) ;
}
} |