当前位置:  编程技术>.net/c#/asp.net

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

    来源: 互联网  发布时间:2014-10-25

    本文导语:  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;...

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} rn",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 + "rn";
                        }
                    }
                    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 += "已经从服务器断开连接rn";
                    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 += "未与服务器建立连接rn";
                }
            }
            catch (Exception)
            {
                textBox1.Text += "未与服务器建立连接rn";
            }
        }
        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 += "已经从服务器断开连接rn";
                            Clinet.Close();
                            Clinet = null;
                            return;
                        }

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

    
 
 

您可能感兴趣的文章:

  • c#多线程更新窗口(winform)GUI的数据
  • c# winform 关闭窗体时同时结束线程实现思路
  • c#多线程读取注册表 c#多线程的小例子
  • C#实现终止正在执行的线程
  • c#后台线程访问前台控件并显示信息示例
  • C#线程间不能调用剪切板的解决方法
  • C#实现线程池的简单示例
  • c# 多线程操作progressBar进度条控件的例子
  • C#子线程更新UI控件的方法实例总结
  • C#实现窗体与子线程的交互的方法
  • C#通过接口与线程通信(捕获线程状态)示例代码
  • C#利用子线程刷新主线程分享教程
  • 描述C#多线程中lock关键字的使用分析
  • C#中的多线程多参数传递详解
  • C# 多线程更新进度条progressBar控件的代码一例
  • C# 多线程复制文件并显示进度条的代码
  • c#(asp.net)线程配置总结
  • c#线程同步的问题与实例分析
  • c#多线程中Lock()关键字的用法小结
  • c#钩子本线程内消息拦截的方法
  • c#线程间传递参数详解
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • 大家来讨论一下,一个客户端一个线程好,还是线程池好?
  • jsp的线程中如何向客户端输出?
  • 请问关于socket客户端因事件启动新线程的问题.高手请进
  • 由同一个服务端创建两个线程分别向两个客户端同时发送不同的数据···
  • 客户端如果不使用多线程可以实现收发同时进行吗?
  • c语言socket多线程编程限制客户端连接数
  • 如何来停止一个等待接收客户端数据的线程;
  • 我写了一个linux下的socket(服务器客户端)+多线程的小程序,可是服务端总是收不到东西,哪个高人帮我看看
  • 使用pthread库实现openssl多线程ssl服务端和客户端
  • Java中多线程相关类Thread介绍
  • 一个进程创建了两个线程,如何使得当任何一个线程(比如线程a)结束时,同时也结束线程b,也就是使两个线程一起死掉,怎么办呢?
  • Windows和Linux下C++类成员方法作为线程函数方法介绍
  • java 线程,对当前线程(非主线程)调用sleep,为什么主线程(窗口)也没反应了
  • c++的boost库多线程(Thread)编程(线程操作,互斥体mutex,条件变量)详解
  • 如何实现一个线程组内多线程的非同不执行,即一个线程执行完毕后再执行下一个线程???
  • Linux下GCC内置原子操作函数(多线程资源访问)介绍
  • 请问:进程创建的线程是怎样运行的啊,线程的处理函数运行完了,线程就退出了吗?
  • .net/c#/asp.net iis7站长之家
  • 请问Linux核心支持多线程吗?开发库有线程库吗?线程好用吗?(稳定?)
  • 请问,在一个进程中创建多线程时如何能避免不同的线程获得同一个线程标识
  • 我的一个多线程服务里, 总是有一个线程莫名其妙的变成僵尸线程。
  • 能否通过线程id控制线程的状态?或是观察到线程的状态?
  • 如何在一个线程中启动另外一个线程,然后本线程就退出?
  • 我要设置一个线程的优先级, 这个属性结构并没有线程的id,它怎么知道是设置哪个线程呢?
  • 请问在java多线程中,是只有run(){}内的代码运行在一个新线程下呢?还是这个类中的代码都运行在一个新线程下?
  • gcc链接的库,分不分单线程版本的和多线程版本的?
  • 内核栈~ 内核线程 ~用户线程 之间关系 问题
  • 子线程的数据如何返回给主线程?
  • 如果父线程死掉 那么子线程会不会死掉呢
  • 多线程为何比单线程慢许多?


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3