欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-14 17:33:58
本文实例讲述了c#简单聊天程序实现方法。分享给大家供大家参考。具体如下: 假如有服务器端程序,chatserver和客户端程序chatclient.实现客户端向服务器端发...

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