C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#实现简单聊天程序

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

作者:聪明的笨蛋

这篇文章主要介绍了C#实现简单聊天程序的方法,实例分析了C#聊天程序的原理与客户端、服务器端的实现技巧,需要的朋友可以参考下

本文实例讲述了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;
//连接server
private 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#程序设计有所帮助。

您可能感兴趣的文章:
阅读全文