| >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 )
{ 上一页 [1] [2] [3] [4] [5] [6] 下一页 |