zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c#多线程网络聊天程序代码分享(服务器端和客户端)

c#多线程网络客户端 分享 聊天 服务器端 程序代码
2023-06-13 09:15:13 时间

XuLIeHua类库

复制代码代码如下:


usingSystem;
usingSystem.Collections; 
usingSystem.Collections.Generic;
usingSystem.Threading; 
usingSystem.Runtime.Serialization;
usingSystem.Runtime.Serialization.Formatters.Binary;
usingSystem.Text;
usingSystem.IO;
usingSystem.Net;  
usingSystem.Net.Sockets;
namespaceXuLIeHua
{
   [Serializable]
   publicstructNetMsg
   {
       publicIPAddressFip;    //发送者的IP。
       publicstringmsg;       //发送的消息。
       publicIPAddressJieIP;  //接收者的ip。
       publicintport;         //端口。
   }
   publicclassXuLIe
   {
       ///<summary>
       ///序列化
       ///</summary>
       ///<param></param>
       ///<returns></returns>
       publicstaticbyte[]ObjToByte(objectobj)
       {
           byte[]tmp=null;
           MemoryStreamfs=newMemoryStream();
           try
           {
               BinaryFormatterXu=newBinaryFormatter();
               Xu.Serialize(fs,obj);
               tmp=fs.ToArray();
           }
           catch(Exceptionerr)
           {
               throwerr;
           }
           finally
           {
               fs.Close();
           }
           returntmp;
       }
       ///<summary>
       ///反列化
       ///</summary>
       ///<param></param>
       ///<returns></returns>
       publicstaticobjectByteToObj(byte[]tmp)
       {
           MemoryStreamfs=null;
           objectobj=null;
           try
           {
               fs=newMemoryStream(tmp);
               fs.Position=0;
               BinaryFormatterXu=newBinaryFormatter();
               obj=Xu.Deserialize(fs);
           }
           catch(Exceptionerr)
           {
               throwerr;
           }
           finally
           {
               fs.Close();
           }
           returnobj;
       }
   }
   publicclassServerJieShou
   {
       privatestaticTcpClientClient;
       publicThreadth;
       privateArrayListArr;
       privateLogTextlog;
       privateboolTiao=true;
       privateTimertime1;
       privateTimerCallbacktime;
       publicServerJieShou(TcpClientsClient,ArrayListarr)
       {
           log=newLogText("连接");
           Client=sClient;
           Arr=arr;
           th=newThread(newThreadStart(ThSub));
           th.IsBackground=true;
           th.Start();
           time=newTimerCallback(XinTiao);
           time1=newTimer(time,null,15000,-1);

       }
       privatevoidXinTiao(objectstate)
       {
           if(Tiao==true)
           {
               Tiao=false;
           }
           else
           {
               Client=null;
           }
       }
       privatevoidThSub()
       {
           try
           {
               while(Client!=null)
               {
                   NetworkStreamNet=Client.GetStream();
                   if(Net.DataAvailable==true)//有数据。
                   {
                       byte[]tmp=newbyte[1024];
                       if(Net.CanRead==true)
                       {
                           MemoryStreammemory=newMemoryStream();
                           memory.Position=0;
                           intlen=1;
                           while(len!=0)
                           {
                               if(Net.DataAvailable==false){break;}
                               len=Net.Read(tmp,0,tmp.Length);
                               memory.Write(tmp,0,len);
                           }
                           log.LogWriter("接收完毕"); 
                           NetMsgmsg=(NetMsg)XuLIe.ByteToObj(memory.ToArray());
                           log.LogWriter("序列化完毕");
                           TcpClienttcpclient=newTcpClient();
                           log.LogWriter("建立TCP对象");
                           if(msg.Fip!=null)//非心跳包。
                           {
                               try
                               {
                                   tcpclient.Connect(msg.JieIP,msg.port);
                                   NetworkStreamSubNet=tcpclient.GetStream();
                                   byte[]Tmp=XuLIe.ObjToByte(msg);
                                   SubNet.Write(Tmp,0,Tmp.Length);
                               }
                               catch(SocketException)
                               {
                                   msg.msg="对方不在线";
                                   byte[]Tmp=XuLIe.ObjToByte(msg);
                                   Net.Write(Tmp,0,Tmp.Length);
                               }
                           }
                           else
                           {
                               if(msg.msg=="QUIT")
                               {
                                   Arr.Remove(Client);
                                   return;
                               }
                           }
                           tcpclient.Close();
                           GC.Collect();
                       }
                   }
                   else//没有数据。
                   {
                   }
                   Thread.Sleep(1000);
               }
           }
           catch
           {
               Arr.Remove(Client);
               th.Abort(); 
           }
       }
   }
}

日志输出类

复制代码代码如下:


usingSystem;
usingSystem.Text;
usingSystem.IO; 
usingSystem.Windows.Forms;
namespaceXuLIeHua
{
 ///<summary>
 ///错误日志的输出。
 ///</summary>
 publicclassLogText
 {
 privatestringAppPath;
 privateStreamWriterStrW;
 privatestringFileName;
 publicLogText(stringFileName1)
 {
  AppPath=Application.StartupPath+@"\Log";
  try
  {
   if(Directory.Exists(AppPath)==false)
   {
    Directory.CreateDirectory(AppPath);  
   }
   if(File.Exists(AppPath+@"\"+FileName+".log")==false)
   {
    File.Create(AppPath+@"\"+FileName+".log");
   }
   FileName=FileName1;
  }
  catch{}
 }
 publicvoidLogWriter(stringText)
 {
  try
  {
   StrW=newStreamWriter(AppPath+@"\"+FileName+".log",true);
   StrW.WriteLine("时间:{0}描述:{1}\r\n",DateTime.Now.ToString(),Text);
   StrW.Flush();
   StrW.Close();
  }
  catch{}
 }
 }
}

服务器

复制代码代码如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.IO;
usingSystem.Net;
usingSystem.Threading;
usingXuLIeHua;
usingSystem.Net.Sockets;   
usingSystem.Collections;
namespace服务器
{
   publicpartialclassfrmServer:Form
   {
       publicfrmServer()
       {
           InitializeComponent();
       }
       privateArrayListarr;
       privateTcpListenerServer1;
       privateTcpClientcol;
       privateArrayListLianJIe;
       privatevoidfrmServer_Load(objectsender,EventArgse)
       {
           arr=newArrayList();
           LianJIe=newArrayList();
           Server1=newTcpListener(Dns.GetHostAddresses(Dns.GetHostName())[0],8000);
           Server1.Start();
           timer1.Enabled=true;
       }
       privatevoidtimer1_Tick(objectsender,EventArgse)
       {
           try
           {

               if(Server1.Pending()==true)
               {
                   col=Server1.AcceptTcpClient();
                   arr.Add(col);
                   XuLIeHua.ServerJieShouserver=newServerJieShou(col,arr);
                   LianJIe.Add(server); 
               }

               if(arr.Count==0){return;}
               listBox1.Items.Clear();
               foreach(TcpClientColinarr)
               {
                   IPEndPointip=(IPEndPoint)Col.Client.RemoteEndPoint;
                   listBox1.Items.Add(ip.ToString());
               }
           }
           catch(Exceptionerr)
           {
               MessageBox.Show(err.Message);
              //Application.Exit(); 
           }
       }
       privatevoidfrmServer_FormClosing(objectsender,FormClosingEventArgse)
       {
           try
           {

               foreach(XuLIeHua.ServerJieShou ColinLianJIe)
               {
                   Col.th.Abort();  
                   Col.th.Join();  
               }
               foreach(TcpClientColinarr)
               {

                   Col.Close();
               }
           }
           finally
           {
               Application.Exit();
           }
       }

   }
}

客户端

复制代码代码如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Threading;
usingSystem.Runtime.Serialization;
usingSystem.Runtime.Serialization.Formatters.Binary;
usingSystem.IO;
usingSystem.Net;
usingSystem.Net.Sockets;
usingXuLIeHua;
namespace客户端
{
   publicpartialclassfrmClinet:Form
   {
       publicfrmClinet()
       {
           InitializeComponent();
       }
       privateTcpClientClinet;
       privateNetworkStreamnet;
       privatevoidbutton3_Click(objectsender,EventArgse)
       {
           try
           {
               Clinet=newTcpClient();
               Clinet.Connect(Dns.GetHostAddresses(textBox2.Text)[0],8000);
               this.Text="服务器连接成功";
               Threadth=newThread(newThreadStart(JieShou));
               th.Start();
               timer1.Enabled=true; 
           }
           catch(SocketException)
           {
               Clinet.Close();
               Clinet=null;
           }

       }
       privatevoidJieShou()
       {
           try
           {
               while(Clinet!=null)
               {
                   net=Clinet.GetStream();
                   if(net.CanWrite==false){Clinet=null;return;}
                   if(net.DataAvailable==true)
                   {
                       byte[]tmp=newbyte[1024];
                       MemoryStreammemory=newMemoryStream();
                       intlen=1;
                       while(len!=0)
                       {
                           if(net.DataAvailable==false){break;}
                           len=net.Read(tmp,0,tmp.Length);
                           memory.Write(tmp,0,len);
                       }
                       if(memory.ToArray().Length!=4)
                       {
                           NetMsgmsg=(NetMsg)XuLIe.ByteToObj(memory.ToArray());
                           textBox1.Text+=msg.Fip.ToString()+"说:"+msg.msg+"\r\n";
                       }
                   }
                   Thread.Sleep(200); 
               }
           }
           catch(Exceptionerr)
           {
               lock(textBox1)
               {
                   textBox1.Text=err.Message;
               }
           }
       }
       privatevoidfrmClinet_FormClosing(objectsender,FormClosingEventArgse)
       {
           if(net.CanWrite==true)
           {
               NetMsgmsg=newNetMsg();
               msg.msg="QUIT";
               byte[]tmp=XuLIe.ObjToByte(msg);
               try
               {
                   net.Write(tmp,0,tmp.Length);
               }
               catch(IOException)
               {
                   textBox1.Text+="已经从服务器断开连接\r\n";
                   Clinet.Close();
                   Clinet=null;
                   return;
               }
           }
           Clinet=null;
           GC.Collect();
           Application.ExitThread(); 
       }
       privatevoidbutton1_Click(objectsender,EventArgse)
       {
           try
           {
               if(Clinet!=null)
               {
                   if(net!=null)
                   {
                       NetMsgmsg=newNetMsg();
                       msg.Fip=Dns.GetHostAddresses(Dns.GetHostName())[0];
                       msg.JieIP=Dns.GetHostAddresses(textBox3.Text)[0];
                       msg.msg=textBox4.Text;
                       byte[]tmp=XuLIe.ObjToByte(msg);
                       net.Write(tmp,0,tmp.Length);
                   }
               }
               else
               {
                   textBox1.Text+="未与服务器建立连接\r\n";
               }
           }
           catch(Exception)
           {
               textBox1.Text+="未与服务器建立连接\r\n";
           }
       }
       privatevoidtimer1_Tick(objectsender,EventArgse)
       {
           try
           {
               if(Clinet!=null)
               {
                   if(net.CanWrite==true)
                   {
                       NetMsgmsg=newNetMsg();
                       msg.msg="0000";
                       byte[]tmp=XuLIe.ObjToByte(msg);
                       try
                       {
                           net.Write(tmp,0,tmp.Length);
                       }
                       catch(IOException)
                       {
                           textBox1.Text+="已经从服务器断开连接\r\n";
                           Clinet.Close();
                           Clinet=null;
                           return;
                       }

                   }
               }
               else
               {
                   textBox1.Text+="未与服务器建立连接\r\n";
               }
           }
           catch(Exceptionerr)
           {
               textBox1.Text+=err.Message+"r\n";
           }
       }
   }
}