2

HI i am quite new to NET programming. I had to develop an application where the client needs to access a server through a LAN, and receive data from a remote MS ACCESS database. The communication is successful and the server is sending the data table in XML format. How ever when the client receives the string and try to convert it to XML and fill a datagridview, it gives an error

"Hexadecimal value 0x00 is a invalid character"

Any help solving this would be appreciated. I used both ASCII encoding and UTF-8 encoding but both didn't work.

This is the client sending the request

    Dim client As New Net.Sockets.TcpClient
    Dim stream As NetworkStream = Nothing
    sql = "Select * from Roll "

    client.Connect("127.0.0.1", 3000)
    stream = client.GetStream
    Dim sendbytes() As Byte = Encoding.ASCII.GetBytes(sql)
    stream.Write(sendbytes, 0, sendbytes.Length)

And then the server receives it and run the query on database and send the datatable over the LAN connection

        client = server.AcceptTcpClient
        stream = client.GetStream
        Dim rvcBytes(client.ReceiveBufferSize) As Byte
        stream.Read(rvcBytes, 0, client.ReceiveBufferSize)
        Dim recive As String = Encoding.ASCII.GetString(rvcBytes)


    Try 'lotNumberFrom & " and LotNumber " & lotNumberTo


        cmd = New OleDbCommand(recive, con)
        '  MsgBox(recive)
        ds.Clear()

        adapter.SelectCommand = cmd
        adapter.Fill(ds, "Batch data")

        Dim writer As New System.IO.StringWriter
        ds.Tables("Batch data").WriteXml(writer, True)

        ' MsgBox(writer.ToString)
        Dim sendbytes() As Byte = Encoding.ASCII.GetBytes(writer.ToString)
        stream.Write(sendbytes, 0, sendbytes.Length)





    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

Then the client recieves it and tries to fill the datagridview. Thats where the problem occurs.

    Dim rvcBytes(client.ReceiveBufferSize) As Byte
    stream.Read(rvcBytes, 0, client.ReceiveBufferSize)
    Dim recive As String = Encoding.ASCII.GetString(rvcBytes)
    Dim dsa As New DataSet



    dsa.ReadXml(New XmlTextReader(New StringReader(recive)))
    DataGridView1.DataSource = dsa.Tables(0)

    client.Close()
4

1 に答える 1

0

コードを微調整することから始めましたが、情報を検索しているときに、MSDN の例をいくつか見つけました。

同期サーバー ソケットの例
http://msdn.microsoft.com/en-CA/library/6y0e13d3.aspx

同期クライアント ソケットの例
http://msdn.microsoft.com/en-CA/library/kb5kfec7.aspx

それらから大いに借りて、私は次のことを思いつきました。(これらは C# で書かれていますが、VB.NET に変換するのはそれほど難しくありません。)

ACE_Server.exe はコンソール アプリケーションです。Ctrl+で強制終了するまで、接続をリッスンし続けますC

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketListener
{
    // Incoming data from the client.
    public static string data = null;

    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        IPHostEntry ipHostEntry = Dns.GetHostEntry("localhost");
        IPAddress ipAddress = ipHostEntry.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and 
        // listen for incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                data = null;

                // An incoming connection needs to be processed.
                while (true)
                {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (data.IndexOf("<EOF>") > -1)
                    {
                        break;
                    }
                }

                // Show the data on the console.
                Console.WriteLine("Text received : {0}", data);

                // do the database stuff
                string sql = data.Substring(0, data.Length - 5);  // remove "<EOF>" terminator
                var con = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\__tmp\testData.accdb;");
                var cmd = new System.Data.OleDb.OleDbCommand(sql, con);
                var adapter = new System.Data.OleDb.OleDbDataAdapter();
                adapter.SelectCommand = cmd;
                var ds = new System.Data.DataSet();
                adapter.Fill(ds, "Batch data");

                var sw = new System.IO.StringWriter();
                ds.Tables["Batch data"].WriteXml(sw, System.Data.XmlWriteMode.IgnoreSchema);

                // send the data back to the client.
                byte[] msg = Encoding.ASCII.GetBytes(sw.ToString());
                int bytesSent = handler.Send(msg);
                Console.WriteLine(bytesSent.ToString() + " bytes sent.");
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }

    public static int Main(String[] args)
    {
        StartListening();
        return 0;
    }
}

ACE_Client.exe は Windows フォーム アプリケーションです。"<EOF>"サーバーコンポーネントがいつ読み取りを停止するかを知ることができるように、SQL文字列に追加されることに注意してください。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace ACE_Client
{
    public partial class Form1 : Form
    {
        public static string data = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];

            // Establish the remote endpoint for the socket.
            // This example uses port 11000 on the local computer.
            IPHostEntry ipHostEntry = Dns.GetHostEntry("localhost");
            IPAddress ipAddress = ipHostEntry.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP  socket.
            Socket sock = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);
            sock.Connect(remoteEP);

            string sql = "SELECT * FROM ExpenseDetails";
            byte[] msg = Encoding.ASCII.GetBytes(sql + "<EOF>");

            // Send the data through the socket.
            int bytesSent = sock.Send(msg);

            // Receive the response from the remote device.
            data = null;
            while (true)
            {
                bytes = new byte[1024];
                int bytesRec = sock.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                if (data.IndexOf("</NewDataSet>") > -1)
                {
                    break;
                }
            }

            // Release the socket.
            sock.Shutdown(SocketShutdown.Both);
            sock.Close();

            var dsa = new DataSet();
            dsa.ReadXml(new System.Xml.XmlTextReader(new System.IO.StringReader(data)));
            dataGridView1.DataSource = dsa.Tables[0];
        }
    }
}
于 2013-05-16T18:39:45.630 に答える