1.设计界面:
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private Thread td;//声明线程对象
private TcpListener tcpListener; //声明侦听对象
private static string message = "";//记录发送的消息
private void frmMain_Load(object sender, EventArgs e)
{
td = new Thread(new ThreadStart(StartListen));//实例化线程类对象
td.Start();//启动线程
timer1.Start();//启动计时器
}
private void StartListen()//监听
{
message = "";//清空消息
tcpListener = new TcpListener(2029);//实例化侦听对象
tcpListener.Start();//开始监听
while(true)
{
TcpClient tclient = tcpListener.AcceptTcpClient();//接受连接请求
NetworkStream nstream = tclient.GetStream();// 获取数据流
byte[] mbyte = new byte[100];//建立缓存
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 strmsg = "" + tbName.Text + "(" + ip[1].ToString() + ")" + DateTime.Now.ToLongTimeString() + "\n" +
this.rtbSend.Text + "\n";//定义消息格式
TcpClient client = new TcpClient(tbIp.Text, 2029);//实例化TcpClient对象
NetworkStream netStream = client.GetStream();//实例化NetworkStream网络流对象
StreamWriter wstream = new StreamWriter(netStream,Encoding.Default);//实例化数据写入对象
wstream.Write(strmsg);//将消息写入网络流
wstream.Flush();//释放网络流对象
wstream.Close();//关闭网络流对象
client.Close();//关闭TcpClient
rtbContent.AppendText(strmsg);//将发送的消息添加到文本框
rtbSend.Clear();//清空发送消息文本框
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void timer1_Tick(object sender, EventArgs e)//计时器
{
if(message!="")
{
rtbContent.AppendText(message);//将接收到的消息添加到文本框中
rtbContent.ScrollToCaret();//自动滚动文本框的滚动条
message = "";
}
}
private void frmMain_FormClosed(object sender, FormClosedEventArgs e) //窗体关闭
{
if (tcpListener != null)//判断侦听对象是否关闭
tcpListener.Stop();//停止侦听
if(td!=null)//判断线程是否为空
{
if (td.ThreadState == ThreadState.Running)//判断线程是否正在运行
td.Abort();//终止线程
}
}
}