我想使用 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 块和必要的变量都已声明..请回复..