首页 > 编程 > C# > 正文

C#实现简单聊天程序的方法

2020-01-24 01:46:52
字体:
来源:转载
供稿:网友

本文实例讲述了C#简单聊天程序实现方法。分享给大家供大家参考。具体如下:

假如有服务器端程序,ChatServer和客户端程序ChatClient.实现客户端向服务器端发送信息的简单功能.

运行步骤,

1.先是服务器端start listen,
2.然后客户端connect.
3.客户端发送消息
 
只要服务器端start listen了,然后客户端也connect了.这样建立起连接后.接受发送信息就方便了,只要用writer,reader去操作NetworkStream
 
服务器ChatServer
创建一个WinForm页面
引用命名空间:

using System.Net.Sockets;using System.Net;using System.IO;using System.Threading;public class ChatServer{private int port = 54321; //端口号private IPAddress ip = IPAddress.Parse("10.20.30.40"); //ip地址private TcpListener tcpListener= null;private TcpClient tcpClient = null;private NetworkStream networkStream = null;private BinaryReader reader;//private BinaryWriter writer;private string getInfo = string.empty;//开始监听private void btnStartListen_Click(object sender, EventArgs e){   tcpListener= new TcpListener( ip , port);   tcpListener.Start(); //开始监听   Thread acceptClientMsgThread= new Thread(AcceptClientMsg);   //运行一个线程去处理客户端发来的信息   acceptClientMsgThread.Start();}//处理客户端发来的信息private void AcceptClientMsg() {  tcpClient = tcpListener.AcceptTcpClient();  if( tcpClient != null)  {    networkStream = tcpClient.GetStream();    reader = new BinaryReader( networkStream);    while (true){     getInfo += reader.ReadString();  //读取客户端发来的信息    }  }}//假如还要显示信息的话,可以整个显示按钮(当然最好的办法是用些线程)//然后点击button后让信息显示出来txtShowClientMsg.Text = getInfo;//如果服务器端想再给客户端发信息,就可以整个发送按钮.然后添加如下代码//string sendMsg = txtSendMsge.Text;//writer = new BinaryWriter( networkStream);//writer.write( sendMsg);}

客户端ChatClient

using System.Net.Sockets;using System.Net;using System.IO;using System.Threading;public class ChatClient{ private int port = 54321;private IPAddress ip = IPAddress.Parse("10.20.30.40");private TcpClient tcpClient = null;private NetworkStream networkStream = null;//private BinaryReader reader;private BinaryWriter writer;//连接serverprivate void btnStartConnect_Click(object sender, EventArgs e){ tcpClient = new TcpClient(); tcpClient.Connect( ip, port); networkStream = tcpClient.GetStream();}//发送信息private void btnStartConnect_Click(object sender, EventArgs e){ string sendMsg = txtSendMsg.Text; writer = new BinaryWriter( networkStream); writer.Write( sendMsg); //发送信息}//如果还要接受server的消息的话.//reader = new BinaryReader( networkStream);//string getInfo = reader.ReadString();}

希望本文所述对大家的C#程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表