服务器端:
1)新建TcpListener 对象,并初始化
private TcpListener tcpListener;
private TcpClient client;
private NetworkStream netStream;
private StreamReader streamR;
private StreamWriter streamW;
private Thread MainThread;
private Thread thread;
private void Start()
{
tcpListener = new TcpListener(IPAddress.Parse(this.txtIp.Text), 8080); //输入ip 和端口
tcpListener.Start(); //开始监听
client = tcpListener.AcceptTcpClient(); //知道客户端有连接
tcpListener.Stop(); //关闭监听。
netStream = client.GetStream(); //获取从客户端发送过来的数据流
streamR = new StreamReader(netStream, Encoding.Default);
streamW = new StreamWriter(netStream, Encoding.Default);
thread = new Thread(new ThreadStart(Reading));
thread.Start();
}
2)读取客户端发送过来的消息
private void Reading() //读取内容
{
for (int i = 0; i < 4; i++)//经测试发现,mySread.ReadLine()在每一次聊天内容发送之后要读四次, //这是查阅资料找到的具体原因我也不清楚,希望知道的人可以告诉我一下
{ //第一次便是头部标志信息行,第二次读取的是聊天内容,
if (i == 0) //最后两次读取的内容为空,依此设计此显示和染色函数
{
string youmsg = "\r\n" + sr.ReadLine();
rtxtLog.AppendText(youmsg);
}
else
{
string youmsg = "\r\n" + sr.ReadLine();
rtxtLog.AppendText(youmsg);
}
}
}
3)向客户端发送消息 button_事件
private void btnSend_Click(object sender, EventArgs e)
{
streamW.WriteLine(new DateTime().ToShortDateString()+"来自服务器的消息");
streamW.WriteLine(this.txtContent.Text);
streamW.Flush();
}
客户端:
1) 建立连接
client = new TcpClient();
client.Connect(IPAddress.Parse("127.0.0.1"), 8080);
netStream = client.GetStream(); //获取从服务器端的数据流
sr = new StreamReader(netStream, Encoding.Default);
sw = new StreamWriter(netStream, Encoding.Default);
myThread = new Thread(new ThreadStart(Reading));
myThread.Start();
MessageBox.Show("连接成功");
2)读取数据的方法
private void Reading()
{
for (int i = 0; i < 4; i++)//经测试发现,mySread.ReadLine()在每一次聊天内容发送之后要读四次,
{ //第一次便是头部标志信息行,第二次读取的是聊天内容,
if (i == 0) //最后两次读取的内容为空,依此设计此显示和染色函数
{
string youmsg = "\r\n" + sr.ReadLine();
rtxtLog.AppendText(youmsg);
}
else
{
string youmsg = "\r\n" + sr.ReadLine();
rtxtLog.AppendText(youmsg);
rtxtLog.Select(rtxtLog.TextLength - youmsg.Length + 1, youmsg.Length);
rtxtLog.SelectionColor = Color.Red;
}
}
}
3)发送数据
private void btnSend_Click(object sender, EventArgs e)
{
sw.WriteLine("时间:"+new DateTime().ToShortDateString()+"来自客户端的消息");
sw.WriteLine(this.txtInfo.Text);
sw.Flush();
//client.sen
}
测试的时候先启用服务器端程序,ip输入127.0.0.1 然后开启客户端程序。即可测试。 /Files/hantianwei/TcpAppTest.rar