最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

c#多線程網(wǎng)絡(luò)聊天程序代碼分享(服務(wù)器端和客戶端)

 更新時(shí)間:2013年12月09日 10:32:41   作者:  
本程序使用VS2005 制作,程序分為三塊,XuLIeHua類庫(kù)下有我寫的把結(jié)構(gòu)序列化的類,還有就是服務(wù)器端和客戶端

XuLIeHua類庫(kù)

復(fù)制代碼 代碼如下:

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;     //發(fā)送者的IP。
        public string msg;        //發(fā)送的消息。
        public IPAddress JieIP;   //接收者的ip。
        public int port;          //端口。
    }
    public class XuLIe
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param ></param>
        /// <returns></returns>
        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;
        }
        /// <summary>
        /// 反列化
        /// </summary>
        /// <param ></param>
        /// <returns></returns>
        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) //有數(shù)據(jù)。
                    {
                        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對(duì)象");
                            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 = "對(duì)方不在線";
                                    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 //沒有數(shù)據(jù)。
                    {
                    }
                    Thread.Sleep(1000);
                }
            }
            catch
            {
                Arr.Remove(Client);
                th.Abort(); 
            }
        }
    }
}

日志輸出類

復(fù)制代碼 代碼如下:

using System;
using System.Text;
using System.IO; 
using System.Windows.Forms;
namespace XuLIeHua
{
 /// <summary>
 /// 錯(cuò)誤日志的輸出。
 /// </summary>
 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("時(shí)間:{0} 描述:{1} \r\n",DateTime.Now.ToString(),Text);
    StrW.Flush();
    StrW.Close();
   }
   catch{}
  }
 }
}

服務(wù)器

復(fù)制代碼 代碼如下:

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 服務(wù)器
{
    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();
            }
        }

    }
}

客戶端

復(fù)制代碼 代碼如下:

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 = "服務(wù)器連接成功";
                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() + "說(shuō): " + 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 += "已經(jīng)從服務(wù)器斷開連接\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 += "未與服務(wù)器建立連接\r\n";
                }
            }
            catch (Exception)
            {
                textBox1.Text += "未與服務(wù)器建立連接\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 += "已經(jīng)從服務(wù)器斷開連接\r\n";
                            Clinet.Close();
                            Clinet = null;
                            return;
                        }

                    }
                }
                else
                {
                    textBox1.Text += "未與服務(wù)器建立連接\r\n";
                }
            }
            catch (Exception err)
            {
                textBox1.Text += err.Message +"r\n";
            }
        }
    }
}

相關(guān)文章

  • C#9.0推出的4個(gè)新特性介紹

    C#9.0推出的4個(gè)新特性介紹

    這篇文章介紹了C#9.0推出的4個(gè)新特性,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-02-02
  • C#中反射和擴(kuò)展方法如何運(yùn)用

    C#中反射和擴(kuò)展方法如何運(yùn)用

    這篇文章主要為大家詳細(xì)介紹了C#中反射和擴(kuò)展方法的運(yùn)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • C#合并多種格式文件為PDF的方法

    C#合并多種格式文件為PDF的方法

    這篇文章主要為大家詳細(xì)介紹了C#合并多種格式文件為PDF的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • 使用Nopcommerce為商城添加滿XX減XX優(yōu)惠券功能

    使用Nopcommerce為商城添加滿XX減XX優(yōu)惠券功能

    中秋國(guó)慶節(jié)眼看到跟前了,很多商城都借此機(jī)會(huì)搞促銷活動(dòng),什么滿200減80送優(yōu)惠券等活動(dòng),基于后臺(tái)程序是怎么實(shí)現(xiàn)的呢?下面腳本之家小編帶領(lǐng)大家一起學(xué)習(xí)吧
    2015-09-09
  • C#連接操作 MySQL 數(shù)據(jù)庫(kù)實(shí)例(使用官方驅(qū)動(dòng))

    C#連接操作 MySQL 數(shù)據(jù)庫(kù)實(shí)例(使用官方驅(qū)動(dòng))

    這篇文章主要介紹了C#連接操作 MySQL 數(shù)據(jù)庫(kù)實(shí)例(使用官方驅(qū)動(dòng)),本文講解了C#中的Mysql連接方法和SQL操作方法,需要的朋友可以參考下
    2015-02-02
  • C# 中使用隱式和顯式操作符的示例

    C# 中使用隱式和顯式操作符的示例

    這篇文章主要介紹了C# 中使用隱式和顯式操作符的示例,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-04-04
  • C#利用Random得隨機(jī)數(shù)求均值、方差、正態(tài)分布的方法

    C#利用Random得隨機(jī)數(shù)求均值、方差、正態(tài)分布的方法

    這篇文章主要介紹了C#利用Random得隨機(jī)數(shù)求均值、方差、正態(tài)分布的方法,涉及C#數(shù)學(xué)運(yùn)算及概率統(tǒng)計(jì)的相關(guān)技巧,需要的朋友可以參考下
    2015-05-05
  • 如何解決hash沖突

    如何解決hash沖突

    上篇文章 為什么哈希存取比較快?使用它需要付出什么代價(jià) 只是簡(jiǎn)單介紹了使用hash所帶來(lái)的利與弊。并未涉及hash的技術(shù)細(xì)節(jié),本文則著重學(xué)習(xí)一下如何解決哈希編址的沖突問(wèn)題。
    2016-06-06
  • C#使用正則表達(dá)式實(shí)現(xiàn)常見的格式驗(yàn)證

    C#使用正則表達(dá)式實(shí)現(xiàn)常見的格式驗(yàn)證

    這篇文章主要為大家詳細(xì)介紹了C#如何使用正則表達(dá)式實(shí)現(xiàn)常見的格式驗(yàn)證,例如:電話號(hào)碼、密碼、郵編等,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • c# 實(shí)現(xiàn)簡(jiǎn)單的串口通訊

    c# 實(shí)現(xiàn)簡(jiǎn)單的串口通訊

    這篇文章主要介紹了c# 如何實(shí)現(xiàn)簡(jiǎn)單的串口通訊,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-03-03

最新評(píng)論

德阳市| 三门峡市| 泗水县| 台东市| 邛崃市| 九龙坡区| 县级市| 枞阳县| 南康市| 嵩明县| 延长县| 韩城市| 天等县| 黄山市| 怀仁县| 小金县| 舒城县| 循化| 佛冈县| 陆良县| 永靖县| 昭苏县| 资源县| 鄂尔多斯市| 蒙山县| 乐陵市| 蓝田县| 襄樊市| 天全县| 吴忠市| 新余市| 普宁市| 普定县| 福清市| 隆尧县| 凌海市| 湾仔区| 四川省| 营口市| 察哈| 上高县|