1

我想使用 C# 中的 XML 文件将 DataTable 从服务器发送到客户端。我在服务器端使用了以下代码

DataSet ds = new DataSet();
ds.WriteXml(nw, XmlWriteMode.WriteSchema);

其中 nw 是服务器上的 NetworkStream

以下代码在客户端

DataSet ds = new DataSet();
ds.ReadXml(clientSockStream, XmlReadMode.ReadSchema);

服务器正在发送数据,但在客户端,程序停止了。服务器端:

tcpserver = new TcpListener(IPAddress.Any, 4444);
tcpserver.Start();
Socket serverSocket = tcpserver.AcceptSocket(); // accepting connection
    if (serverSocket.Connected)
    {
        serversockstream = new NetworkStream(serverSocket);
        serverStreamReader = new StreamReader(serversockstream);
        serverStreamWriter = new StreamWriter(serversockstream);
        handleClinet client = new handleClinet(); 
        client.startClient(serverStreamReader, serversockstream,serverStreamWriter);
    }

    public void startClient(StreamReader streamReader, NetworkStream ser, StreamWriter streamWriter)
    {
        this.sread = streamReader;
        this.swrite = streamWriter;
        this.nwstram = ser;
        Thread ctThread = new Thread(handleClients);
        ctThread.Start();
    }

    private void handleClients()
    {
        // Creating Dummy DataTable to send to Client...
        DataSet ds = new DataSet();
        DataTable d = new DataTable();
        d.Columns.Add("Name");
        d.Columns.Add("City");
        d.Rows.Add("John","USA");

        ds.Tables.Add(d);

        try
        {    

            while ((true))
            {
                String mystr = sread.ReadLine();
                if (mystr.Equals("sendTable"))
                    break;
            }
            swrite.WriteLine("done");
            swrite.Flush();
            if(nwstram.CanWrite)
            {
                MessageBox.Show("it can write...");
                ds.WriteXml(nwstram, XmlWriteMode.IgnoreSchema);
            }
            nwstram.Flush();
            MessageBox.Show("XML Sent");

        }

客户端:

    tcpClient = new TcpClient("127.0.0.1", 4444);

    IPHostEntry ip = Dns.GetHostEntry("127.0.0.1");
    //get a network stream from server
    clientSockStream = tcpClient.GetStream();
    clientStreamReader = new StreamReader(clientSockStream);
    clientStreamWriter = new StreamWriter(clientSockStream);

    private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            clientStreamWriter.WriteLine("sendTable");
            clientStreamWriter.Flush();
            DataSet ds = new DataSet();
            String str = "";
            while (true)
            {
                str = clientStreamReader.ReadLine();
                if (str.Equals("done"))
                    break;

            }
            //MessageBox.Show("Client :" + str);
            if (clientSockStream.CanRead)
            {
                ds.ReadXml(clientSockStream, XmlReadMode.IgnoreSchema);
            }
        }
        dataGridView1.DataSource = ds.Tables[0];
    }

假设所有 catch 块和必要的变量都已声明..请回复..

4

1 回答 1

0

我不确定我是否看到了你所有的代码,但这里有一个例子,如果我不得不使用 TcpSockets 而不是 WCF,我会做什么。

服务器端

public void StartServer()
{
    TcpListener listener = null;
    TcpClient client = null;
    NetworkStream nwStream = null; 

    try
    {
        listener = new TcpListener(IPAddress.Any, 4444);
        listener.Start();
    }
    catch(Exception ex)
    { Console.WriteLine(ex.Message); }

    byte[] buffer = new byte[1024];

    try
    {
        bool waiting = true;

        while(waiting)
        {
            if(listener.Pending())
            {

                client = listener.AcceptTcpClient();
                nwStream = client.GetStream();

                using(var ms = new MemoryStream())
                {
                    CreateDataSet().WriteXml(ms);
                    ms.Position = 0;

                    int read = 0;
                    while((read = ms.Read(buffer, 0, 1024)) != 0)
                    {
                        nwStream.Write(buffer, 0, read);
                    }
                }
                nwStream.Flush();
                nwStream.Close();
                client.Close();
                waiting = false;
            }
        }
    }
    catch(Exception ex)
    {
       Console.WriteLine(ex.Message);
    }
}

private DataSet CreateDataSet()
{
    //Create your dataset here and return something
}

客户端

public DataSet GetDataSet()
{
    DataSet ds = new DataSet();
    TCPClient client = null;
    NetworkStream nwStream = null;

    try
    {
        client = new TcpClient("127.0.0.1", 4444);
        nwStream = client.GetStream();

        using(var ms = new MemoryStream())
        {
            byte[] buffer = new byte[1024];
            int read = 0;
            while((read = nwStream.Read(buffer, 0, 1024)) != 0)
            {
                ms.Write(buffer, 0, read);
            }
            ms.Position = 0;

            ds.ReadXml(ms);
        }
    }
    finally
    {
        nwStream.Close();
        client.Close();
    }

    return ds;
}

我不会说这会完全按照您的意愿工作,但是进行一些修改应该是一个好的开始。但是,我强烈建议研究 WCF(我是一个巨大的支持者),因为这是您在某些代码中的相同服务的框架。

WCF 服务器端

[ServiceContract]
public interface IDataService
{
    [OperationContract]
    DataSet GetData();
}

public class DataService: IDataService
{
    public DataSet GetData()
    {
        //return some dataset here
    }
}

WCF 客户端

private DataSet GetDataSet()
{
    DataSet ds;

    //This would be utilizing some gerated code, or you can make your own client
    var client = new DataServiceClient(someEndPoint, someBinding);
    client.Open();

    ds = client.GetData();

    client.Close();
    return ds;
}

同样,这不是完全有效的代码,而只是一个示例,说明为什么 WCF 如此受欢迎,而不是通过套接字编写自己的疯狂代码。如果您希望保持语言中立,您甚至可以升级到 http 套接字,它仍然可以与 Java 一起使用,只要它是 SOAP 标准(有一些功能,如可靠消息传递,与 .网)。

于 2012-11-05T15:02:01.920 回答