标签:state 获取 port pcl 线程 17. art 网络服务 监听
实现效果:
知识运用:
TcpListener TcpClient 和 NetworkStream类 及 Timer组件
1> TcpListener类 //用来从Tcp网络客户端侦听连接
2> TcpClient类 //为Tcp网络服务提供客户端连接
public TcpClient(string hostname,int port) //远程主机的DNS名 端口号
3> NetworkStream类 //提供在阻止模式下通过Stream套接字发送和接受数据的方法
//其Read方法用于从NetworkStream类读取数据
public override int Read(byte[] buffer,int offset,int size)
4> notifyIcon控件的Icon属性
实现代码:
//该方法用于监听指定端口 并通过该端口发送消息 private void StartListen() { tcpListener = new TcpListener(888); //创建TcpListener对象 tcpListener.Start(); //开始监听 while (true) { TcpClient client = tcpListener.AcceptTcpClient(); //接受连接请求 NetworkStream nstream = tcpListener.AcceptTcpClient().GetStream(); //获取数据流 byte[] mbyte = new byte[1024]; //建立缓存 int i = nstream.Read(mbyte, 0, mbyte.Length); //将数据流写入缓存 message = Encoding.Default.GetString(mbyte, 0, i); //获取传输的内容 } } private void button2_Click(object sender, EventArgs e) { try { //IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName()); //获取本机地址 string message = "干得好,赏啤酒一箱"; //传输的内容 TcpClient client = new TcpClient(textBox1.Text, 888); //创建TcpClient对象 NetworkStream netstream = client.GetStream(); //创建NetworkStream对象 StreamWriter wstream = new StreamWriter(netstream, Encoding.Default); //创建StreamWriter对象 wstream.Write(message); //将信息写入流 wstream.Flush(); wstream.Close(); //关闭流 client.Close(); //关闭TcpClent对象 } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } bool k = true; //一个标记用于控制图标闪动 private void timer1_Tick(object sender, EventArgs e) { if (message.Length > 0) { //如果网络中传输了数据 notifyIcon1.Text = message; if (k) { notifyIcon1.Icon = Properties.Resources._1; //托盘图标为1 k = false; } else { notifyIcon1.Icon = Properties.Resources._2; //托盘图标为2 k = true; } } } private void Form1_Load(object sender, EventArgs e) { td = new Thread(new ThreadStart(this.StartListen)); //通过线程调用StartListen方法 td.Start(); //开始运行线程 } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (tcpListener != null) { tcpListener.Stop(); //停止侦听对象 } if (td != null) { if (td.ThreadState == ThreadState.Running) //判断线程是否运行 td.Abort(); //终止线程 } } private void button1_Click(object sender, EventArgs e) { message = ""; //清空传输内容 }
标签:state 获取 port pcl 线程 17. art 网络服务 监听
原文地址:https://www.cnblogs.com/feiyucha/p/10127480.html