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

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

可以处理的,步骤为:

1客户端服务器连(用Socket通讯)

2客户端向处服务器发送SQL语句,如搜索一个表的数据

3服务器接到请求,执行SQL语句返回一个DataTable

4服务器将这个DataTable进行序列化、并且压缩

5服务器将序列化和压缩后的byte[] msg数组传给客户端

6客户端收到byte[] msg数组先进行解压缩、和反序列化为DataTable

7再将DataTable通过DataSet和SqlDataAdapterUpdate(Table)存在SQL中

下面我只给一些关键的代码,我有实现过的

第一步客户端==》连接服务器并通讯,主要是发送SQL给服务器返回一个DataTable表

using System;

using SystemCollectionsGeneric;

using SystemComponentModel;

using SystemData;

using SystemDrawing;

using SystemLinq;

using SystemText;

using SystemWindowsForms;

using SystemNet;

using SystemNetSockets;

using SystemXml;

using SystemXmlSerialization;

using SystemIO;

using SystemIOCompression;

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 = IPAddressParse("1162583127");

IPAddress local = IPAddressParse("127001");//可改为远程IP地址

IPEndPoint iep = new IPEndPoint(local, 6060);

try

{

client = new Socket(AddressFamilyInterNetwork, SocketTypeStream, ProtocolTypeTcp);

clientConnect(iep);

}

catch (SocketException)

{

ConsoleWriteLine("无法连接到服务器!");

return ;

}

//输入exit,可以断开与服务器的连接

if (str == "")

{

return;

}

//发送SQL语句给服务器

clientSend(EncodingUnicodeGetBytes(str));

//得到实际收到的字节总数

Int32 rec = clientReceive(buf);

ConsoleWriteLine(EncodingASCIIGetString(buf, 0, rec));

//接收服务器返回的数据

returnData = SystemTextEncodingUnicodeGetString(buf,0,rec);

//将returnData解压缩后,再反序列化转成DataTable dt = DeserializerDataTable(Decompress(returnData));

ConsoleWriteLine("断开与服务器的连接");

clientClose();

dataGridView1DataSource = dt;

}

//将DataTable表反序列化

private DataTable DeserializerDataTable(string pXml)

{

StringReader strReader = new StringReader(pXml);

XmlReader xmlReader = XmlReaderCreate(strReader);

XmlSerializer serializer = new XmlSerializer(typeof(DataTable));

DataTable dt = serializerDeserialize(xmlReader) as DataTable;

return dt; }

//给服务器传SQL语句

private void buttonSearch_Click(object sender, EventArgs e)

{

string Sql = StringFormat("Select top {0} From Part Where CorpCode_='PT'", textBox1TextTrim()); ;

ClientTest(Sql);

}

#region 压缩和解压缩

public string Compress(string str)

{

byte[] buffer = EncodingUnicodeGetBytes(str);

MemoryStream ms = new MemoryStream();

using (GZipStream zip = new GZipStream(ms, CompressionModeCompress, true))

{

zipWrite(buffer, 0, bufferLength);

}

msPosition = 0;

MemoryStream outStream = new MemoryStream();

byte[] compressed = new byte[msLength];

msRead(compressed, 0, compressedLength);

byte[] gzBuffer = new byte[compressedLength + 4];

SystemBufferBlockCopy(compressed, 0, gzBuffer, 4, compressedLength);

SystemBufferBlockCopy(BitConverterGetBytes(bufferLength), 0, gzBuffer, 0, 4);

return ConvertToBase64String(gzBuffer);

}

//解压缩

public string Decompress(string compressedText)

{

byte[] gzBuffer = ConvertFromBase64String(compressedText);

using (MemoryStream ms = new MemoryStream())

{

int msgLength = BitConverterToInt32(gzBuffer, 0);

msWrite(gzBuffer, 4, gzBufferLength - 4);

byte[] buffer = new byte[msgLength];

msPosition = 0;

using (GZipStream zip = new GZipStream(ms, CompressionModeDecompress))

{

zipRead(buffer, 0, bufferLength);

}

return EncodingUnicodeGetString(buffer);

}

}

#endregion

}

}

第二步服务器收到SQL语句执行,并回传一个表给客户端

服务器接到请求,执行SQL语句返回一个DataTable

服务器将这个DataTable进行序列化、并且压缩

服务器将序列化和压缩后的byte[] msg数组传给客户端

using System;

using SystemCollectionsGeneric;

using SystemComponentModel;

using SystemData;

using SystemDrawing;

using SystemLinq;

using SystemText;

using SystemWindowsForms;

using SystemNet;

using SystemNetSockets; //可以使用套接

using SystemThreading; //可以使用多线程

using SystemDataSqlClient;

using SystemXml;

using SystemXmlSerialization;

using SystemIO;

using SystemIOCompression;

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 = DnsGetHostName();

IPHostEntry host = DnsGetHostByName(name);

IPAddress id= hostAddressList[0];

/

//IPAddress local = IPAddressParse("1921680100");

IPEndPoint iep = new IPEndPoint(IPAddressAny, 6060);

server = new Socket(AddressFamilyInterNetwork, SocketTypeStream, ProtocolTypeTcp);

// 将套接字与本地终结点绑定

serverBind(iep);

//在本地13000端口号上进行监听

serverListen(10);

while (true)

{

// 得到包含客户端信息的套接字

client = serverAccept();

//创建消息服务线程对象ClientService方法委托给线程

Thread newthread = new Thread(new ThreadStart(ClientService));

// 启动消息服务线程

newthreadStart();

}

}

private Int32 i;

private void ClientService()

{

Socket s = client;

String data = null;

String returnData = null;

byte[] bytes = new byte[1024];

while ((i = sReceive(bytes)) != 0)

{

//接收客户端的SQL

data = SystemTextEncodingUnicodeGetString(bytes, 0, i);

//将接到的String 执行SQL返回表

DBAccess obj = new DBAccess(); //专门传给SQL的类相当于DBHELP

DataTable dt = objFillData(data, "TEST", 1);//执行SQL返回表

//将返回的表转为String,并将returnData压缩

returnData = objCompress(objSerializeDataTableXml(dt));

byte[] msg = SystemTextEncodingUnicodeGetBytes(returnData);

// 发送数据表给客户端 sSend(msg);

if ((i = sReceive(bytes)) == 0)

continue;

}

//关闭套接字

sClose();

}

}

//DBAccess的部份代码

class DBAccess

{

#region DataTable序列化与反序列化

public string SerializeDataTableXml(DataTable dt)

{

StringBuilder sb = new StringBuilder();

XmlWriter writer = XmlWriterCreate(sb);

XmlSerializer serializer = new XmlSerializer(typeof(DataTable));

serializerSerialize(writer, dt);

writerClose();

return sbToString(); }

public DataTable DeserializerDataTable(string pXml)

{

StringReader strReader = new StringReader(pXml);

XmlReader xmlReader = XmlReaderCreate(strReader);

XmlSerializer serializer = new XmlSerializer(typeof(DataTable));

DataTable dt = serializerDeserialize(xmlReader) as DataTable;

return dt; }

#endregion

#region 压缩和解压缩

public string Compress(string str)

{

byte[] buffer = EncodingUnicodeGetBytes(str);

MemoryStream ms = new MemoryStream();

using (GZipStream zip = new GZipStream(ms, CompressionModeCompress, true))

{

zipWrite(buffer, 0, bufferLength);

}

msPosition = 0;

MemoryStream outStream = new MemoryStream();

byte[] compressed = new byte[msLength];

msRead(compressed, 0, compressedLength);

byte[] gzBuffer = new byte[compressedLength + 4];

SystemBufferBlockCopy(compressed, 0, gzBuffer, 4, compressedLength);

SystemBufferBlockCopy(BitConverterGetBytes(bufferLength), 0, gzBuffer, 0, 4);

return ConvertToBase64String(gzBuffer);

}

public string Decompress(string compressedText)

{

byte[] gzBuffer = ConvertFromBase64String(compressedText);

using (MemoryStream ms = new MemoryStream())

{

int msgLength = BitConverterToInt32(gzBuffer, 0);

msWrite(gzBuffer, 4, gzBufferLength - 4);

byte[] buffer = new byte[msgLength];

msPosition = 0;

using (GZipStream zip = new GZipStream(ms, CompressionModeDecompress))

{

zipRead(buffer, 0, bufferLength);

}

return EncodingUnicodeGetString(buffer);

}

}

#endregion

}

第三步调用DataSet和SqlDataAdapterUpdate(Table)存在SQL中,这个是传入一个DataGridView ,可在客户端中使用保存(部份代码,没有连接SQL数据库的)

#region 公共保存DataGridView

public bool DataGridViewSave(DataTable table,string tableName,string CorpCode)

{

string Sql = StringFormat("Select Top 0 From {0} Where CorpCode_='{1}' ", tableName, CorpCode);

SqlDataAdapter sda = new SqlDataAdapter(thisCreateCommand(Sql, null, 1));

SqlCommandBuilder scb = new SqlCommandBuilder(sda);

sdaUpdate(table);

thisClose();

return true;

}

#endregion

socket存取数据效率高。在应用层通过传输层进行数据通信时,socket存取数据效率要高于数据库,所以要用socket。socket指套接字。所谓套接字,就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。

接收到的数据是byte[]数组格式的,需要进行一步简单的转换。如果你第一步接收已经做完了,那么可能这步转换就省了

byte[] byts=new byte[102410242];//定义接收数组,大小为2m根据需要,一般设置为1就够了,因为简单接收,不会有太大数据量的。

int length=socketReceive(byts, 0, bytsLength, SocketFlagsNone);//开始接收数据,并将接收到数据放到byts数组中。它的返回值为一个整型,是指接收数据的数量

if(length>0)

{

string msg = SystemTextEncodingUTF8GetString(byts, 0, r);

}

OK,到这步,你应该就会了吧,此时拿到的msg就是接收到回来的字符串了。然后启动数据库连接,将msg写入对应的表就可以了。

以上就是关于C# 怎样才能实现客户端通过服务器端连接数据库服务器全部的内容,包括:C# 怎样才能实现客户端通过服务器端连接数据库服务器、为什么要用socket用数据库不行吗、c#中怎么把socket接收的数据存入数据库等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/10191424.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-06
下一篇 2023-05-06

发表评论

登录后才能评论

评论列表(0条)

保存