这个是Tcp的公共类.因为考虑到要多线程.所以所有的对象和方法全部都是实例化的!!!  没有静态的.using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net.Sockets;
namespace SynchronizationSysTem.SysBll
{
    public class TcpHelper
    {
        static SynchronizationSysTem.BLL.WrongLog wr = new SynchronizationSysTem.BLL.WrongLog();
        static TcpClient tclient;
        static bool status = false;
        /// <summary>
        /// 创建服务器端
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <returns>返回一个被指定了IP和端口的服务器端</returns>
        public static TcpListener createService(int port)
        {
            tlistener = new TcpListener(port);
            return tlistener;
        }        /// <summary>
        /// 创建客户端
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <param name="port">端口</param>
        /// <returns>返回一个被指定了IP和端口的TCP/IP客户端</returns>
        public TcpClient ThreadcreateClient(string ip, int port)
        {
            try
            {
                TcpClient tclient = new TcpClient(ip, port);
                return tclient;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }        /// <summary>
        /// 开启服务器端
        /// </summary>
        /// <param name="tl"></param>
        public static void openListener(TcpListener tl)
        {
            try
            {
                tl.Start();
                status = true;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }        /// <summary>
        /// 关闭服务器端
        /// </summary>
        /// <param name="tl"></param>
        public static void closeListener(TcpListener tl)
        {
            try
            {
                tl.Stop();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }        /// <summary>
        /// 关闭服务器端
        /// </summary>
        /// <param name="tc"></param>
        public static void closeClient(TcpClient tc)
        {
            try
            {
                tc.Close();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }        /// <summary>
        /// 服务器端接受数据
        /// </summary>
        /// <param name="tl">服务器端对象</param>
        /// <returns>转化为string的数据</returns>
        public static string getListenerData(TcpListener tl)
        {
            try
            {
                
                TcpClient tclient = tl.AcceptTcpClient();
                NetworkStream ns = tclient.GetStream();
                Byte[] bytebuffer = new Byte[1024];
                //
                int temp = ns.Read(bytebuffer, 0, bytebuffer.Length);
                string msg = System.Text.Encoding.Default.GetString(bytebuffer, 0, temp);
                closeClient(tclient);
                return msg;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                return null;
            }
            finally
            {
                closeListener(tl);            }
        }
        /// <summary>
        /// 多线程获取Tcp服务器端数据
        /// </summary>
        /// <param name="o">方法所需参数,因使用了线程池,故将需要的数据封装到一个object对象中</param>
        /// <returns></returns>
        public static string getListenerData(object o)
        {
            try
            {
                TcpListener tl = (TcpListener)o;
                openListener(tl);
                TcpClient tclient = tl.AcceptTcpClient();
                NetworkStream ns = tclient.GetStream();
                Byte[] bytebuffer = new Byte[1024];
                //
                int temp = ns.Read(bytebuffer, 0, bytebuffer.Length);
                string msg = System.Text.Encoding.Default.GetString(bytebuffer, 0, temp);
                closeClient(tclient);
                return msg;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                return null;
            }
        }
        
        /// <summary>
        /// 客户端接收数据
        /// </summary>
        /// <param name="tc">客户端对象</param>
        /// <returns>转化为string的数据</returns>
        public static string getClientData(TcpClient tc)
        {
            try
            {
                
                NetworkStream ns = tc.GetStream();
                Byte[] bytebuffer = new Byte[1024];
                int temp = ns.Read(bytebuffer, 0, bytebuffer.Length);
                string msg = System.Text.Encoding.Default.GetString(bytebuffer, 0, temp);
                ns.Close();
                return msg;            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                return null;
            }
            finally
            {
                closeClient(tc);            }
        }                /// <summary>
        /// 客户端发送数据
        /// </summary>
        /// <param name="str">数据字符串</param>
        /// <param name="tc">TCP/IP客户端</param>
        /// <returns></returns>
        public bool ThreadclientSend(string str, TcpClient tc)
        {
            try
            {
                NetworkStream ns = tc.GetStream();
                Byte[] bytebuffer = System.Text.Encoding.Default.GetBytes(str);
                ns.BeginWrite(bytebuffer, 0, bytebuffer.Length, null, null);
                ns.Close();
                return true;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                return false;
            }
            finally
            {
                tc.Close();
            }
        }        /// <summary>
        /// 客户端发送数据
        /// </summary>
        /// <param name="o"></param>
        public static void clientSend(object o)
        {
            try
            {
                Dictionary<string, string> dic = (Dictionary<string, string>)o;
                tclient = new TcpClient(dic["IP"].ToString(), Convert.ToInt32(dic["Port"].ToString()));
                NetworkStream ns = tclient.GetStream();
                Byte[] bytebuffer = System.Text.Encoding.Default.GetBytes(dic["Str"].ToString());
                ns.Write(bytebuffer, 0, bytebuffer.Length);
                ns.Close();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
}

解决方案 »

  1.   

    这个就是我的数据发送类了.有些方法是调用Bll层的对表的修改啊什么的..那些可以不用太过的考虑.同样的,那些方法都是实例方法不是静态的.对象也是实例化对象.没有静态的.using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Net.Sockets;
    using System.Diagnostics;
    using System.Collections;
    using System.Data;
    namespace SynchronizationSysTem.SysBll
    {
        public class SendSource
        {
            #region 执行发送
            /// <summary>
            /// 执行发送
            /// </summary>
            /// <param name="dt">查询出来的数据</param>
            /// <param name="ip">要发送的IP地址</param>
            /// <param name="port">使用的端口</param>
            static StringBuilder sourcestr;
            private static void Send(DataTable dt,string ip,int port,string AutoNum)
            {
                /*/获取数据字符串并使用内部协议
                 * 数据类型+数据的AutoNum+数据字符串
                 * */
                if (!CheckDataTable(dt))
                    return;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    try
                    {
                        TcpHelper tch = new TcpHelper();
                        sourcestr = new StringBuilder(dt.Rows[i]["CollectionValue"].ToString());
                        TcpClient tc = tch.ThreadcreateClient(ip, port);
                        if (tc == null)
                        {
                            return;
                        }
                        tch.ThreadclientSend(sourcestr.ToString() + "-----" + dt.Rows[i]["AutoNum"].ToString(), tc);
                        //更新最后一行
                        SynchronizationSysTem.Model.Allocations sma = new SynchronizationSysTem.Model.Allocations();
                        sma.AutoNum = Convert.ToInt32(Convert.ToInt32(AutoNum));
                        sma.AutonumValue = dt.Rows[i]["AutoNum"].ToString();
                        SynchronizationSysTem.BLL.Allocations sba = new SynchronizationSysTem.BLL.Allocations();
                        sba.ThreadUpdate(sma);
                        //单条发送完毕以后的间隔时间
                        //Thread.Sleep(1000);
                    }
                    catch (Exception ex)
                    {
                        //出错情况
                        SynchronizationSysTem.BLL.WrongLog wr = new SynchronizationSysTem.BLL.WrongLog();
                        SynchronizationSysTem.Model.WrongLog wrm = new SynchronizationSysTem.Model.WrongLog();
                        wrm.ServerIP = ip;
                        wrm.WrongValue = "IP:" + ip + ",Port:" + port + ",AutoNum:" + dt.Rows[i]["AutoNum"].ToString() + ",错误信息:" + ex.Message;
                        wrm.WrongTime = DateTime.Now;
                        wr.Add(wrm);
                        Console.Write(ex.Message);
                        /*
                         * 如果出错,则将AutoNum改为前一条数据的AutoNum
                         * **/
                        SynchronizationSysTem.Model.Allocations sma = new SynchronizationSysTem.Model.Allocations();
                        sma.AutoNum = Convert.ToInt32(Convert.ToInt32(AutoNum));
                        sma.AutonumValue = (Convert.ToInt32(dt.Rows[i]["AutoNum"].ToString()) - 1).ToString();
                        SynchronizationSysTem.BLL.Allocations sba = new SynchronizationSysTem.BLL.Allocations();
                        sba.ThreadUpdate(sma);
                    }
                    
                    
                }
            }
            #endregion        #region 验证DataTable是否为空
            /// <summary>
            /// 验证DataTable是否为空
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            private static bool CheckDataTable(DataTable dt)
            {
                if (dt == null)
                    return false;
                if (dt.Rows.Count < 1)
                    return false;
                return true;
            }
            #endregion        //用来暂停线程的全局变量
            public static bool status = false;
            //用来存储服务器信息
            static DataTable serverdt;        #region 用来给外部调用的发送方法
            /// <summary>
            /// 封装好的发送方法
            /// </summary>
            /// <param name="baseType"></param>
            /// <param name="OperateType"></param>
            public static void Senders(string baseType, string OperateType,int SomeTime,int SingelTime)
            {            //获取服务器信息
                serverdt = SynchronizationSysTem.BLL.Servers.GetList("Status=1 and Type <>" + baseType + " and IP<>'127.0.0.1'").Tables[0];
                if (!CheckDataTable(serverdt))
                    return;
                while (status)
                {
                    for (int i = 0; i <2; i++)
                    {
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("DataRow", serverdt.Rows[i]);
                        dic.Add("OperateType", OperateType);
                        WaitCallback wc = new WaitCallback(Sending);
                        ThreadPool.QueueUserWorkItem(wc, dic);
                        //每一条线程开启间隔时间
                        Thread.Sleep(5000);
                    }
                    //发送完一轮数据以后,间隔时间
                    Thread.Sleep(5000);
                }
            }
            #endregion        #region 多线程调用的发送方法,内部使用
            /// <summary>
            /// 发送
            /// </summary>
            /// <param name="o"></param>
            private static void Sending(object o)
            {
                Dictionary<string, object> dic1 = (Dictionary<string, object>)o;
                DataRow dr = (DataRow)dic1["DataRow"];
                string OperateType = dic1["OperateType"].ToString();            SynchronizationSysTem.BLL.Allocations sba = new SynchronizationSysTem.BLL.Allocations();
                DataTable allocationdt = sba.ThreadGetList(@"ServerType=2 and OperateType=" + OperateType + " and DatabaseName='"
                                                                                                + dr["DatabaseName"].ToString() + "' and IP='" + dr["IP"].ToString() + ":" + dr["LinsterPort"].ToString() + "'").Tables[0];
                if (!CheckDataTable(allocationdt))
                    return;
                SynchronizationSysTem.BLL.SQLTabel sbs = new SynchronizationSysTem.BLL.SQLTabel();
                DataTable sqldt = sbs.ThreadGetList("ServerType=2 and OperateType=" + OperateType).Tables[0];
                //验证是否有SQL语句
                if (!CheckDataTable(sqldt))
                    return;
                string sqlstr = sqldt.Rows[0]["BaseSQL"].ToString();
                /*
                 * 填充SQL语句:
                 * SQL语句原型为:select top #count# from 表名 where AutoNum<#AutonumValue#
                 * **/
                sqlstr = sqlstr.Replace("#count#", allocationdt.Rows[0]["Numbers"].ToString());
                sqlstr = sqlstr.Replace("#AutoNum#", allocationdt.Rows[0]["AutonumValue"].ToString());
                //执行SQL语句返回一个DataTable
                DataTable sourcedt = new DataTable();
                if (OperateType == "1")
                {
                    SynchronizationSysTem.BLL.CollectionCalllog callogbus = new SynchronizationSysTem.BLL.CollectionCalllog();
                    sourcedt = callogbus.GetSome1(sqlstr);
                }
                else
                {
                    SynchronizationSysTem.BLL.CollectionOther otherbus = new SynchronizationSysTem.BLL.CollectionOther();
                    sourcedt = otherbus.GetSome1(sqlstr);
                }
                if (!CheckDataTable(sourcedt))
                    return;
                Send(sourcedt, dr["IP"].ToString(), Convert.ToInt32(dr["LinsterPort"].ToString()), allocationdt.Rows[0]["AutoNum"].ToString());
            }
            #endregion        #region 判断DataTalbe是否有数据
            /// <summary>
            /// 判断DataTable是否有数据
            /// </summary>
            /// <param name="processId"></param>
            private static void CheckThread(int processId)
            {
                Process process = Process.GetProcessById(processId);
                ProcessThreadCollection threads = process.Threads;            foreach (ProcessThread thread in threads)
                {
                    Console.Write(thread.ThreadState);
                }        }
            #endregion
        }
    }
    这是TcpLintener的代码,这些代码我是运行在另外一台机器上的.端口我都写死了,用来做实现的.另外一台机器上面.这样的程序我运行了13个.都是独立的一个项目,且生成为.exe文件了.我运行的就是.exe文件.using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net.Sockets;
    namespace TcpLinsterThread
    {
        class Program
        {
            static TcpListener tl = null;
            static TcpClient tclient = null;
            static NetworkStream ns = null;
            static int temp = 0;
            static Byte[] bytebuffer = null;
            static string msg = "";
            static void Main(string[] args)
            {
                Console.WriteLine("服务器端6798");
                //这个端口是写死了的,主要用于做实验.
                tl = new TcpListener(6798);
                tl.Start();
                tclient = tl.AcceptTcpClient();
                ns = tclient.GetStream();
                bytebuffer = new Byte[1024];
                temp = ns.Read(bytebuffer, 0, bytebuffer.Length);
                msg = System.Text.Encoding.Default.GetString(bytebuffer, 0, temp);
                Console.WriteLine(msg);
                while (msg != "exit")
                {
                    //tl = new TcpListener(5678);
                    //tl.Start();
                    tclient = tl.AcceptTcpClient();
                    ns = tclient.GetStream();
                    bytebuffer = new Byte[1024];
                    temp=ns.Read(bytebuffer, 0, bytebuffer.Length);
                    msg = System.Text.Encoding.Default.GetString(bytebuffer, 0,temp);
                    Console.WriteLine(msg);
                }
                if (msg == "exit")
                {
                    Console.WriteLine("接受到结束符:Exit");
                }
            }
        }
    }这里就是主要的几个代码了.至于一些什么BLL层的代码我就不贴了   浪费版面.
    请个位大大  帮我看看.. 是不是那里有问题..
    前一篇帖子我已经给了分了. 
    分也不多了  象征性的给20吧.. 
    请各位大大们帮忙.
      

  2.   

    传输一次,就使用了一个套接字,记得需要关闭这些套接字
    还有没必要传输一次就NEW一个出来吧,只有这个套接字不可用的时候再从新NEW一个