要求用c#编程,如何通过socket发送和接受dataset数据集?高手帮帮忙,急啊!要有例子。

解决方案 »

  1.   

    思路:把DataSet Serilize 成一个Byte[] 通过Socket 发送, 接受端接到 Byte[] 后把它 Deserialize 成 DataSet.
      

  2.   

    说实话LZ这个题目挺大,给你一篇MSDN上的文章,关于如何Serialize DataSet, E文,有一些关键代码:http://msdn.microsoft.com/msdnmag/issues/04/10/CuttingEdge/
      

  3.   

    LZ这个如果不直接用Socket,而是用.NET REMOTING (TCP Channel, Binary Format) 就简单多了,缺点是Remoting传递大量数据时性能不太好.
      

  4.   

    谢谢各位!我用序列化与反序列化了。本地可以跑通了,即没有网络传输时跑通了。
           public static byte[] GetBinaryFormatDataSet(DataSet ds)//序列化
            {
                //创建内存流
                MemoryStream memStream = new MemoryStream();
                //产生二进制序列化格式
                IFormatter formatter = new BinaryFormatter();
                //指定DataSet串行化格式是二进制
                ds.RemotingFormat = SerializationFormat.Binary;
                //串行化到内存中
                formatter.Serialize(memStream, ds);
                //将DataSet转化成byte[]
                byte[] binaryResult = memStream.ToArray();
                //清空和释放内存流
                memStream.Close();
                memStream.Dispose();
                return binaryResult;
            }
            public DataSet RetrieveDataSet(byte[] binaryData)//反序列化
            {
                //创建内存流
                MemoryStream memStream = new MemoryStream(binaryData);
                //memStream.Seek(0, SeekOrigin.Begin);
                //memStream.Position = 0;
                //产生二进制序列化格式
                IFormatter formatter = new BinaryFormatter();
                //反串行化到内存中
                object obj = formatter.Deserialize(memStream);            //类型检验
                if (obj is DataSet)
                {
                    DataSet dataSetResult = (DataSet)obj;
                    return dataSetResult;
                }
                else
                {
                    return null;
                }
            }
      

  5.   

    我发上来,各们大虾帮我看看,哪里出错了?
    我的客户端:using System;
    using System.IO;
    using System.Data;
    using System.Net.Sockets;
    using System.Net;
    using System.Text;
    using System.Data.OleDb;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;namespace xmldataset
    {
        /// <summary>
        /// Class1 的摘要说明。
        /// </summary>
        class Class1
        {
            
            public static byte[] GetBinaryFormatDataSet(DataSet ds)
            {
                //创建内存流
                MemoryStream memStream = new MemoryStream();
                //产生二进制序列化格式
                IFormatter formatter = new BinaryFormatter();
                //指定DataSet串行化格式是二进制
                ds.RemotingFormat = SerializationFormat.Binary;
                //串行化到内存中
                formatter.Serialize(memStream, ds);
                //将DataSet转化成byte[]
                byte[] binaryResult = memStream.ToArray();
                //清空和释放内存流
                memStream.Close();
                memStream.Dispose();
                return binaryResult;
            }
            /// <summary>
            /// 应用程序的主入口点。
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
                //
                // TODO: 在此处添加代码以启动应用程序
                //
                OleDbConnection conn = new OleDbConnection();
                conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "sqldb.mdb";
                conn.Open();
                String selstr = "select * from phonetab";
                OleDbDataAdapter adapter = new OleDbDataAdapter(selstr, conn);
                DataSet ds = new DataSet();
                adapter.Fill(ds, "phonetab");
                conn.Close();
                byte[] input = GetBinaryFormatDataSet(ds);
                try
                {
                    IPAddress ip = System.Net.IPAddress.Parse("127.0.0.1");
                    IPEndPoint ipep = new IPEndPoint(ip, 3434);
                    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                try
                    {
                        server.Connect(ipep);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                    server.Send(input);
                    byte[] response = new byte[1024];
                    int bytesRead = server.Receive(response);
                    Console.WriteLine(Encoding.ASCII.GetString(response, 0, bytesRead));
                    server.Shutdown(SocketShutdown.Both);
                    server.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
    }
      

  6.   

    出什么异常?
    你这个好像没有做分包处理!如果数据量大的话,Socket会自动把数据分成多个包传输!
      

  7.   

    我的服务端:using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Data;
    using System.Net.Sockets;
    using System.Net;
    using System.Data.OleDb;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;namespace helloserver
    {
        class Program
        {
            public static DataSet ds;
            public static DataSet RetrieveDataSet(byte[] binaryData)
            {
                //创建内存流
                MemoryStream memStream = new MemoryStream(binaryData);
                memStream.Seek(0, SeekOrigin.Begin);
                //产生二进制序列化格式
                IFormatter formatter = new BinaryFormatter();
                //反串行化到内存中
                object obj = formatter.Deserialize(memStream);
                //类型检验
                if (obj is DataSet)
                {
                    DataSet dataSetResult = (DataSet)obj;
                    return dataSetResult;
                }
                else
                {
                    return null;
                }
            }
            static void Main(string[] args)
            {            IPAddress ip = System.Net.IPAddress.Parse("127.0.0.1");
                IPEndPoint ipep = new IPEndPoint(ip, 3434);
                Socket lst = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                lst.Bind(ipep);
                lst.Listen(20);            while (true)
                {
                    Console.Write("等待连接.......");
                    Socket client = lst.Accept();
                    Console.WriteLine("客户已连接");                byte[] request = new byte[512];
                    int bytesRead = client.Receive(request);
                    //ds = RetrieveDataSet(request);
                    string input = Encoding.ASCII.GetString(request, 0, bytesRead);                Console.WriteLine("客户请求:{0}", input);                string output = "hello, " + input + "!";
                    byte[] hello = Encoding.ASCII.GetBytes(output);                try
                    {
                        client.Send(hello);
                        client.Shutdown(SocketShutdown.Both);
                        client.Close();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }        }
        }
    }
      

  8.   

    可能就是分包出的错,加了ds = RetrieveDataSet(request);后有异常:未处理的异常:  System.Runtime.Serialization.SerializationException: 在分析完成之
    前就遇到流结尾。
      

  9.   

    你要在封包前面加上封包的长度位,然后根据这个位判断数据是不是完全收到,如果没有完全收到,就继续Receive,直到所以数据都收到了,再把它们拼接起来反序列化!
      

  10.   

    我这是先在本机上测试的,以后再在其他机子上测试。
    高手把代码贴上来吧,不多的,一会就好了,我好想好想要,我急的啊!
    这里不好贴的话,发到我邮箱吧,[email protected],感激涕零。
      

  11.   

    原理很简单
    你发送消息的时候要有一个统一的消息头
    这个消息头的长度是固定的,里面你可以定义一想要的任何字段,比喻你要发送的消息体的长度等信息,把这个消息头和消息体放到一个byte数组当中发送出去,接受的时候首先接受消息头,并得出消息体的长度,然后开始接受消息体长度个byte,然后将消息体分离出来反序列话就可以了
      

  12.   

    //客户端
    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.Net.Sockets;
    namespace newClient
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();                  }        private void Form1_Load(object sender, EventArgs e)
            {
                        }
                private void button1_Click(object sender, EventArgs e)
            {
                int port = 2000;
                string host = "192.168.5.12";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket            listBox1.Items.Add("Conneting...");
                c.Connect(ipe);//连接到服务器
                //string sendStr = "Hello!This is a socket test";
                string sendStr = textBox1.Text;            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                listBox1.Items.Add("Send Message");
                c.Send(bs, bs.Length, 0);//发送测试信息            string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                //MessageBox.Show(recvStr, "Client Get Message:{0}");//显示服务器返回信息
                listBox1.Items.Add(recvStr);//显示服务器返回信息
                c.Close();            //listBox1.Items.Add("Press Enter to Exit");
               
            }
        }
    }
      

  13.   

    //服务端
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Collections;                      
    namespace newServer
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private void Form1_Load(object sender, EventArgs e)
            {        }      
            private void button1_Click(object sender, EventArgs e)
            {
                int port = 2000;
                string host = "192.168.5.12";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket类
                s.Bind(ipe);//绑定2000端口
                s.Listen(0);//开始监听
                listBox1.Items.Add("Wait for connect");
                Socket temp = s.Accept();//为新建连接创建新的Socket。            listBox1.Items.Add("Get a connect");
                string recvStr = "";
                byte[] recvBytes = new byte[1024];            int bytes;
                bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                //MessageBox.Show(recvStr, "Server Get Message:{0}");//把客户端传来的信息显示出来
                listBox1.Items.Add(recvStr);//把客户端传来的信息显示出来
                string sendStr = "Ok!!Client Send Message Sucessful!";
                //string sendStr = textBox1.Text;
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                temp.Send(bs, bs.Length, 0);//返回客户端成功信息
                temp.Close();
                s.Close();
                //listBox1.Items.Add("Press Enter to Exit");
               
            }    }
    }
      

  14.   

    peter_com()给的程序似乎没有分包过程