热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

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

本程序使用VS2005制作,程序分为三块,XuLIeHua类库下有我写的把结构序列化的类,还有就是服务器端和客户端

XuLIeHua类库

代码如下:

using System;
using System.Collections; 
using System.Collections.Generic;
using System.Threading; 
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.IO;
using System.Net;  
using System.Net.Sockets;
namespace XuLIeHua
{
    [Serializable]
    public struct NetMsg
    {
        public IPAddress Fip;     //发送者的IP。
        public string msg;        //发送的消息。
        public IPAddress JieIP;   //接收者的ip。
        public int port;          //端口。
    }
    public class XuLIe
    {
        ///
        /// 序列化
        ///

        ///
        ///
        public static byte[] ObjToByte(object obj)
        {
            byte[] tmp = null;
            MemoryStream fs = new MemoryStream();
            try
            {
                BinaryFormatter Xu = new BinaryFormatter();
                Xu.Serialize(fs, obj);
                tmp = fs.ToArray();
            }
            catch (Exception err)
            {
                throw err;
            }
            finally
            {
                fs.Close();
            }
            return tmp;
        }
        ///
        /// 反列化
        ///

        ///
        ///
        public static object ByteToObj(byte[] tmp)
        {
            MemoryStream fs = null;
            object obj = null;
            try
            {
                fs = new MemoryStream(tmp);
                fs.Position = 0;
                BinaryFormatter Xu = new BinaryFormatter();
                obj = Xu.Deserialize(fs);
            }
            catch (Exception err)
            {
                throw err;
            }
            finally
            {
                fs.Close();
            }
            return obj;
        }
    }
    public class ServerJieShou
    {
        private static TcpClient Client;
        public Thread th;
        private ArrayList Arr;
        private LogText log;
        private bool Tiao = true;
        private Timer time1;
        private TimerCallback time;
        public ServerJieShou(TcpClient sClient, ArrayList arr)
        {
            log = new LogText("连接") ;
            Client = sClient;
            Arr = arr;
            th = new Thread(new ThreadStart(ThSub));
            th.IsBackground = true;
            th.Start();
            time = new TimerCallback(XinTiao);
            time1 = new Timer(time, null, 15000, -1);

        }
        private void XinTiao(object state)
        {
            if (Tiao == true)
            {
                Tiao = false;
            }
            else
            {
                Client = null;
            }
        }
        private void ThSub()
        {
            try
            {
                while (Client != null)
                {
                    NetworkStream Net = Client.GetStream();
                    if (Net.DataAvailable == true) //有数据。
                    {
                        byte[] tmp = new byte[1024];
                        if (Net.CanRead == true)
                        {
                            MemoryStream memory = new MemoryStream();
                            memory.Position = 0;
                            int len = 1;
                            while (len != 0)
                            {
                                if (Net.DataAvailable == false) { break; }
                                len = Net.Read(tmp, 0, tmp.Length);
                                memory.Write(tmp, 0, len);
                            }
                            log.LogWriter("接收完毕"); 
                            NetMsg msg = (NetMsg)XuLIe.ByteToObj(memory.ToArray());
                            log.LogWriter("序列化完毕");
                            TcpClient tcpclient = new TcpClient();
                            log.LogWriter("建立TCP对象");
                            if (msg.Fip != null) //非心跳包。
                            {
                                try
                                {
                                    tcpclient.Connect(msg.JieIP, msg.port);
                                    NetworkStream SubNet = 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(); 
            }
        }
    }
}

日志输出类

代码如下:

using System;
using System.Text;
using System.IO; 
using System.Windows.Forms;
namespace XuLIeHua
{
 ///
 /// 错误日志的输出。
 ///

 public class LogText
 {
  private string AppPath;
  private StreamWriter StrW;
  private string FileName;
  public LogText(string FileName1)
  {
   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{}
  }
  public void LogWriter(string Text)
  {
   try
   {
    StrW = new StreamWriter(AppPath+@"\"+FileName+".log",true);
    StrW.WriteLine("时间:{0} 描述:{1} \r\n",DateTime.Now.ToString(),Text);
    StrW.Flush();
    StrW.Close();
   }
   catch{}
  }
 }
}

服务器

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;
using XuLIeHua;
using System.Net.Sockets;   
using System.Collections;
namespace 服务器
{
    public partial class frmServer : Form
    {
        public frmServer()
        {
            InitializeComponent();
        }
        private ArrayList arr;
        private TcpListener Server1;
        private TcpClient col;
        private ArrayList LianJIe;
        private void frmServer_Load(object sender, EventArgs e)
        {
            arr = new ArrayList();
            LianJIe = new ArrayList();
            Server1 = new TcpListener(Dns.GetHostAddresses(Dns.GetHostName())[0], 8000);
            Server1.Start();
            timer1.Enabled = true;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {

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

                if (arr.Count == 0) { return; }
                listBox1.Items.Clear();
                foreach (TcpClient Col in arr)
                {
                    IPEndPoint ip = (IPEndPoint)Col.Client.RemoteEndPoint;
                    listBox1.Items.Add(ip.ToString());
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
               // Application.Exit(); 
            }
        }
        private void frmServer_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {

                foreach (XuLIeHua.ServerJieShou  Col in LianJIe)
                {
                    Col.th.Abort();  
                    Col.th.Join();  
                }
                foreach (TcpClient Col in arr)
                {

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

    }
}

客户端

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Net;
using System.Net.Sockets;
using XuLIeHua;
namespace 客户端
{
    public partial class frmClinet : Form
    {
        public frmClinet()
        {
            InitializeComponent();
        }
        private TcpClient Clinet;
        private NetworkStream net;
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                Clinet = new TcpClient();
                Clinet.Connect(Dns.GetHostAddresses(textBox2.Text)[0], 8000);
                this.Text = "服务器连接成功";
                Thread th = new Thread(new ThreadStart(JieShou));
                th.Start();
                timer1.Enabled = true; 
            }
            catch (SocketException)
            {
                Clinet.Close();
                Clinet = null;
            }

        }
        private void JieShou()
        {
            try
            {
                while(Clinet != null)
                {
                    net = Clinet.GetStream();
                    if (net.CanWrite == false) { Clinet = null; return;}
                    if (net.DataAvailable == true)
                    {
                        byte[] tmp = new byte[1024];
                        MemoryStream memory = new MemoryStream();
                        int len = 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)
                        {
                            NetMsg msg = (NetMsg)XuLIe.ByteToObj(memory.ToArray());
                            textBox1.Text += msg.Fip.ToString() + "说: " + msg.msg + "\r\n";
                        }
                    }
                    Thread.Sleep(200); 
                }
            }
            catch (Exception err)
            {
                lock (textBox1)
                {
                    textBox1.Text = err.Message;
                }
            }
        }
        private void frmClinet_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (net.CanWrite == true)
            {
                NetMsg msg = new NetMsg();
                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(); 
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (Clinet != null)
                {
                    if (net != null)
                    {
                        NetMsg msg = new NetMsg();
                        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";
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (Clinet != null)
                {
                    if (net.CanWrite == true)
                    {
                        NetMsg msg = new NetMsg();
                        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 (Exception err)
            {
                textBox1.Text += err.Message +"r\n";
            }
        }
    }
}


推荐阅读
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 优化联通光猫DNS服务器设置
    本文详细介绍了如何为联通光猫配置DNS服务器地址,以提高网络解析效率和访问体验。通过智能线路解析功能,域名解析可以根据访问者的IP来源和类型进行差异化处理,从而实现更优的网络性能。 ... [详细]
  • Windows服务与数据库交互问题解析
    本文探讨了在Windows 10(64位)环境下开发的Windows服务,旨在定期向本地MS SQL Server (v.11)插入记录。尽管服务已成功安装并运行,但记录并未正确插入。我们将详细分析可能的原因及解决方案。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 如何配置Unturned服务器及其消息设置
    本文详细介绍了Unturned服务器的配置方法和消息设置技巧,帮助用户了解并优化服务器管理。同时,提供了关于云服务资源操作记录、远程登录设置以及文件传输的相关补充信息。 ... [详细]
  • 本文深入探讨了Linux系统中网卡绑定(bonding)的七种工作模式。网卡绑定技术通过将多个物理网卡组合成一个逻辑网卡,实现网络冗余、带宽聚合和负载均衡,在生产环境中广泛应用。文章详细介绍了每种模式的特点、适用场景及配置方法。 ... [详细]
  • 本文详细分析了Hive在启动过程中遇到的权限拒绝错误,并提供了多种解决方案,包括调整文件权限、用户组设置以及环境变量配置等。 ... [详细]
  • 本文探讨了如何优化和正确配置Kafka Streams应用程序以确保准确的状态存储查询。通过调整配置参数和代码逻辑,可以有效解决数据不一致的问题。 ... [详细]
  • 在现代网络环境中,两台计算机之间的文件传输需求日益增长。传统的FTP和SSH方式虽然有效,但其配置复杂、步骤繁琐,难以满足快速且安全的传输需求。本文将介绍一种基于Go语言开发的新一代文件传输工具——Croc,它不仅简化了操作流程,还提供了强大的加密和跨平台支持。 ... [详细]
  • 本文旨在提供一套高效的面试方法,帮助企业在短时间内找到合适的产品经理。虽然观点较为直接,但其方法已被实践证明有效,尤其适用于初创公司和新项目的需求。 ... [详细]
  • 阿里宝卡用户能否在UC浏览器极速版中享受免流量服务?
    本文详细介绍了UC浏览器极速版是否支持阿里宝卡的免流量功能,以及如何正确设置以确保免流量服务的正常使用。 ... [详细]
  • 苹果系统频繁弹窗提示无法验证服务器身份?竟是网易邮箱证书过期所致
    近日,众多苹果用户发现iOS、iPadOS和macOS系统频繁弹出无法验证服务器身份的警告。问题根源在于网易邮箱未能及时更新其数字证书,导致原证书过期后无法被信任。 ... [详细]
  • 使用C# .NET构建UDP点对点聊天应用
    本文详细介绍如何利用C# .NET框架开发一个基于UDP协议的点对点聊天程序,包括客户端与服务器之间的连接建立、数据传输等核心功能。 ... [详细]
  • Linux双网卡绑定技术详解与实践
    本文详细介绍了如何在Linux系统中实现双网卡绑定,即将两块物理网卡合并为一个逻辑网卡,以提高网络性能和可靠性。文中不仅涵盖了基本的概念,还提供了具体的配置步骤和测试方法。 ... [详细]
  • 梦幻西游挖图奇遇:70级项链意外触发晶清诀,3000W轻松到手
    在梦幻西游中,挖图是一项备受欢迎的活动,无论是小宝图还是高级藏宝图,都吸引了大量玩家参与。通常情况下,小宝图的数量保证了稳定的收益,但特技装备的出现往往能带来意想不到的惊喜。本文讲述了一位玩家通过挖图获得70级晶清项链的故事,最终实现了3000W的游戏币逆袭。 ... [详细]
author-avatar
夜晨在行动
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有