{
try
{
tlTcpListen = new TcpListener ( port ) ;
//以8000端口号来初始化TcpListener实例
tlTcpListen.Start ( ) ;
//开始监听网络的连接请求
statusBar1.Text = "正在监听..." ;
stRead = tlTcpListen.AcceptSocket ( ) ;
//通过连接请求,并获得接收数据时使用的Socket实例
EndPoint tempRemoteEP = stRead.RemoteEndPoint ;
IPEndPoint tempRemoteIP = ( IPEndPoint ) tempRemoteEP ;
//获取请求的远程计算机名称
IPHostEntry host = Dns.GetHostByAddress
( tempRemoteIP.Address ) ;
string sHostName = host.HostName ;
statusBar1.Text = "已经连接!" ;
//循环侦听
while ( blistener )
{
string sTime = DateTime.Now.ToShortTimeString ( ) ;
//获取接收数据时的时间
Byte [ ] byRead =new Byte [ 80 ] ;
int iRead = stRead.ReceiveFrom
( byRead , ref tempRemoteEP ) ;
//获得接收的字节数目
Byte [ ] byText = new Byte [ iRead ] ;
//并根据接收到的字节数目来定义字节数组
Array.Copy ( byRead , 0 , byText , 0 , iRead ) ;
string sTemp = System.Text.Encoding.Default.
GetString ( byText ) ;
//判断是否为断开连接控制码
if ( sTemp.Trim ( ) == "STOP" )
{
stRead.Close ( ) ;
tlTcpListen.Stop ( ) ;
//关闭侦听
statusBar1.Text = "连接已经关闭!" ;
thThreadRead.Abort ( ) ;
//中止线程
return ;
}
else
listBox1.Items.Add ( sTime + " " + sTemp ) ;
} catch ( System.Security.SecurityException )
{
MessageBox.Show ( "侦听失败!" , "错误" ) ;
}
} |