Asp.NET Tutorials
Home > 网络与远程 > VisualC#中托管Socket的实现方法(二)(2)
VisualC#中托管Socket的实现方法(二)(2)
作者:unknown 来自:网络
7.在Form1.cs中的Main函数之后,添加下列代码,下列代码的作用是定义过程“Listen”,此过程的功能是监听“8000”端口号,接收网络中连接请求,建立连接,并获取接收数据时使用的Socket实例,并以Socket实例来接收客户机程序发送来的数据。并根据客户机发送来控制码来断开网络连接,释放资源:

{
   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  (  "侦听失败!"  , "错误"  )  ;
}
}
Add by : Huobazi (2005-6-18:04:21)