日期:2014-05-17  浏览次数:20810 次

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的消息的话.

<