C# 怎样才能实现客户端通过服务器端连接数据库服务器???

各位大虾,小弟初学c#想完成一个简单的C/S程式,但发现很多实例都是通过客户端直接连接数据库,请问需要怎样才能实现 客户端通过服务器端连接数据库服务器???
实现逻辑:
客户端------服务器sever-------数据库sever
希望能够提供出示例。
请帮忙提供出具体实例代码或下载地址。
最新回答
我萌怪我咯

2024-09-18 00:46:31

可以处理的,步骤为:
1.客户端与服务器连(用Socket通讯)
2.客户端向处服务器发送SQL语句,如搜索一个表的数据
3.服务器接到请求,执行SQL语句返回一个DataTable
4.服务器将这个DataTable进行序列化、并且压缩
5.服务器将【序列化和压缩】后的byte[] msg数组传给客户端
6.客户端收到byte[] msg数组先进行解压缩、和反序列化为DataTable
7.再将DataTable通过DataSet和SqlDataAdapter.Update(Table)存在SQL中
下面我只给一些关键的代码,我有实现过的

第一步.客户端==》连接服务器并通讯,主要是发送SQL给服务器返回一个DataTable表
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.IO.Compression;

namespace Client
{
public partial class FormClient : Form
{
DataTable dt;
public FormClient()
{
InitializeComponent();
}

private void ClientTest(string str)
{
Socket client;
String returnData;
byte[] buf = new byte[9991024]; //此处可能有些问题
//IPAddress local = IPAddress.Parse("116.25.83.127");
IPAddress local = IPAddress.Parse("127.0.0.1");//可改为远程IP地址
IPEndPoint iep = new IPEndPoint(local, 6060);
try
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(iep);
}
catch (SocketException)
{
Console.WriteLine("无法连接到服务器!");
return ;
}

//输入exit,可以断开与服务器的连接
if (str == "")
{
return;
}
//发送SQL语句给服务器
client.Send(Encoding.Unicode.GetBytes(str));

//得到实际收到的字节总数
Int32 rec = client.Receive(buf);
Console.WriteLine(Encoding.ASCII.GetString(buf, 0, rec));
//接收服务器返回的数据
returnData = System.Text.Encoding.Unicode.GetString(buf,0,rec);

//将returnData解压缩后,再反序列化转成DataTable dt = DeserializerDataTable(Decompress(returnData));
Console.WriteLine("断开与服务器的连接......");
client.Close();
dataGridView1.DataSource = dt;
}

//将DataTable表反序列化
private DataTable DeserializerDataTable(string pXml)
{
StringReader strReader = new StringReader(pXml);
XmlReader xmlReader = XmlReader.Create(strReader);
XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
DataTable dt = serializer.Deserialize(xmlReader) as DataTable;

return dt; }
//给服务器传SQL语句
private void buttonSearch_Click(object sender, EventArgs e)
{
string Sql = String.Format("Select top {0} * From Part Where CorpCode_='PT'", textBox1.Text.Trim()); ;
ClientTest(Sql);

}
#region 压缩和解压缩
public string Compress(string str)
{
byte[] buffer = Encoding.Unicode.GetBytes(str);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream = new MemoryStream();
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);

byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}

//解压缩
public string Decompress(string compressedText)
{
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (MemoryStream ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.Unicode.GetString(buffer);
}
}

#endregion
}
}

第二步.服务器收到SQL语句执行,并回传一个表给客户端
服务器接到请求,执行SQL语句返回一个DataTable
服务器将这个DataTable进行序列化、并且压缩
服务器将【序列化和压缩】后的byte[] msg数组传给客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets; //可以使用套接字
using System.Threading; //可以使用多线程
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.IO.Compression;

namespace AppServer
{
public partial class FormApp : Form
{
public FormApp()
{
InitializeComponent();
}
private void FormApp_Load(object sender, EventArgs e)
{
// AppService instance = new AppService();
}

private void buttonStartService_Click(object sender, EventArgs e)
{
AppService();

}
private Socket server;
private Socket client;
private void AppService()
{
/*
//本机IP
string name = Dns.GetHostName();
IPHostEntry host = Dns.GetHostByName(name);
IPAddress id= host.AddressList[0];
* */

//IPAddress local = IPAddress.Parse("192.168.0.100");
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 6060);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 将套接字与本地终结点绑定
server.Bind(iep);
//在本地13000端口号上进行监听
server.Listen(10);
while (true)
{
// 得到包含客户端信息的套接字
client = server.Accept();
//创建消息服务线程对象ClientService方法委托给线程
Thread newthread = new Thread(new ThreadStart(ClientService));
// 启动消息服务线程
newthread.Start();
}
}
private Int32 i;
private void ClientService()
{
Socket s = client;
String data = null;
String returnData = null;
byte[] bytes = new byte[1024];

while ((i = s.Receive(bytes)) != 0)
{
//接收客户端的SQL
data = System.Text.Encoding.Unicode.GetString(bytes, 0, i);
//将接到的String 执行SQL返回表
DBAccess obj = new DBAccess(); //专门传给SQL的类相当于DBHELP
DataTable dt = obj.FillData(data, "TEST", 1);//执行SQL返回表

//将返回的表转为String,并将returnData压缩
returnData = obj.Compress(obj.SerializeDataTableXml(dt));
byte[] msg = System.Text.Encoding.Unicode.GetBytes(returnData);

// 发送数据表给客户端 s.Send(msg);
if ((i = s.Receive(bytes)) == 0)
continue;
}
//关闭套接字
s.Close();
}
}

//DBAccess的部份代码

class DBAccess
{
#region DataTable序列化与反序列化
public string SerializeDataTableXml(DataTable dt)
{
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
serializer.Serialize(writer, dt);
writer.Close();

return sb.ToString(); }
public DataTable DeserializerDataTable(string pXml)
{
StringReader strReader = new StringReader(pXml);
XmlReader xmlReader = XmlReader.Create(strReader);
XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
DataTable dt = serializer.Deserialize(xmlReader) as DataTable;

return dt; }
#endregion
#region 压缩和解压缩
public string Compress(string str)
{
byte[] buffer = Encoding.Unicode.GetBytes(str);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream = new MemoryStream();
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);

byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}

public string Decompress(string compressedText)
{
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (MemoryStream ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.Unicode.GetString(buffer);
}
}

#endregion
}

第三步.调用DataSet和SqlDataAdapter.Update(Table)存在SQL中,这个是传入一个DataGridView ,可在客户端中使用保存(部份代码,没有连接SQL数据库的)
#region 公共保存DataGridView
public bool DataGridViewSave(DataTable table,string tableName,string CorpCode)
{
string Sql = String.Format("Select Top 0 * From {0} Where CorpCode_='{1}' ", tableName, CorpCode);
SqlDataAdapter sda = new SqlDataAdapter(this.CreateCommand(Sql, null, 1));
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
sda.Update(table);
this.Close();
return true;
}
#endregion
紫珺婳浅

2024-09-18 00:19:50

你这样的就输入分布式开发,现在流行的主要就是WCF,WebService,Remoting 服务端给出接口,客户端连接到服务器后,只需要调用服务器的方法,具体的业务操作,数据操作都是服务器来执行,如果初学建议去看下WebService相关知识,应该很容易上手
舀一瓢月色

2024-09-18 01:09:36

那就是服务器接口客户端的sql和参数,然后服务端执行sql,把得到的结果序列化后发送出去嘛
或者使用wcf功能
伪友

2024-09-18 00:25:01

08 或之后的用wcf
像05的webservice、remoting
实例网上找找吧
追问
沒有找到這方面的實例,能不能幫忙提供地址呢。
追答
你上msdn上找吧,里面好多教程的,你看你需要什么就找什么的,是在msdn的主页上,你上微软中国可以找到,找不到再MMM吧
咱ゝ么傀゛

2024-09-18 00:06:11

最简单的是使用webservice