实现效果:
知识运用:
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 Thread td; private string message = ""; private TcpListener tcpListener; //监听方法 private void startListen() { tcpListener = new TcpListener(999); tcpListener.Start(); while (true) { TcpClient client = tcpListener.AcceptTcpClient(); NetworkStream netStream = client.GetStream(); byte[] bt=new byte[1024]; netStream.Read(bt,0,bt.Length); message = Encoding.Default.GetString(bt); } } //发送消息 private void button1_Click(object sender, EventArgs e) { TcpClient client = new TcpClient(textBox1.Text,999); string msg = "嗨,你好! 南极鱼"; NetworkStream netStream = client.GetStream(); StreamWriter sw = new StreamWriter(netStream); sw.WriteLine(msg); sw.Flush(); sw.Close(); client.Close(); } //初始化 private void Form1_Load(object sender, EventArgs e) { td = new Thread(new ThreadStart(startListen)); td.Start(); timer1.Start(); } //清理工作 private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (td.ThreadState == ThreadState.Running) td.Abort(); if (tcpListener != null) tcpListener.Stop(); } //定时检查有无消息 bool flag; private void timer1_Tick(object sender, EventArgs e) { if (message.Length > 0) { if(flag) { notifyIcon1.Icon = Properties.Resources._1; flag = false; } else { notifyIcon1.Icon = Properties.Resources._2; flag = true; } } } //停止闪烁 private void button2_Click(object sender, EventArgs e) { message = ""; notifyIcon1.Icon = Properties.Resources._3; }