使用GetPrivateProfileString出现错误

sfw2fly 2005-04-21 07:42:52
var
Jilu1:array[1..100] of char;
//Jilu1:string;
begin
//setlength(Jilu1,100);
If OpenDialog1.Execute then
Logfilename:=Opendialog1.filename;
GetPrivateProfileString('123','abc','',@Jilu1,100,LogfileName);//问题出现行
labeledEdit1.Text:=Jilu1;
end;

==========================================
我使用这段代码时,报告错误“Incompatible types: 'String' and 'PAnsiChar'.哪位知道怎样解决,请告知小弟。
...全文
108 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
halfdream 2005-04-21
  • 打赏
  • 举报
回复
var Jilu1:array[1..100] of char;
......
GetPrivateProfileString('123','abc','',@Jilu1,100,pchar(LogfileName));

sfw2fly 2005-04-21
  • 打赏
  • 举报
回复
谢谢!
存取对象变量库结构作为一个功能较完备的Windows软件开发平台,Visual Basic专业版提供了对数据库应用的强大支持。尤其提供了使用数据控件和绑定控制项,使用数据库存取对象变量(Data Access Object Variable),直接调用ODBC 2.0 API接口函数等三种访问数据库的方法。对其标准内置的Ms Access数据库,它可以提供不弱于专业数据库软件的支持,可以进行完整的数据库维护、操作及其事务处理。在VB中,将非Access数据库称为外来数据库。对于FoxPro、dBASE、Paradox等外来数据库。虽然借助VB的Data Manager 能够对这些数据库进行NEW、OPEN、DESIGN、DELETE等操作,但在应用程序的运行状态中并不能从底层真正实现这些功能。本文从使用数据库存取对象变量的方法出发,实现了非Access格式数据库(以FoxPro数据库为例)的建新库、拷贝数据库结构、动态调入等操作,阐述了从编程技巧上弥补VB对这些外来数据库支持不足的可行性 。 一 、 VB数据库的体系结构具体的VB的数据库结构。 VB数据库的核心结构是所谓的MicroSoft JET数据库引擎,JET引擎的作用就像是一块"面 板",在其上可以插入多种ISAM(Indexed Sequential Access Method,即索引顺序存取方 法) 数据驱动程序。JET引擎为Access格式数据库提供了直接的内部(build-in)支持,这就是VB对Access数据库具有丰富支持的真正原因。 VB专业版中提供了FoxPro、dBASE(或 Xbase)、Paradox、Btrieve等数据库的ISAM驱动程序,这就使得VB能支持这些数据库格 式。另外,其他的许多兼容ISAM的驱动程序也可以通过从厂商的售后服务得到。因而从理论上说,VB能支持所有兼容ISAM的数据库格式(前提是只需获得这些数据库的ISAM驱动接口程序)。 由上可见,Ms JET引擎实质上提供了:一个符合ANSI标准的语法分析器;为查询结果集的使用而提供的内存管理功能;同所支持的数据库的外部接口;为应用代码提供的内部接口。实际上,在VB中从一种数据库类型转化为另一种数据库类型几乎不需要或只需要很少的代码修改。而且,尽管dBASE、Paradox本身的DDL (Data Definition Language,即数据定义语言)和DML(Data Manipulation Language,即数据操纵语言)是非结构化查询的,但它们仍然可以使用VB的SQL语句和JET引擎来操纵。 从VB的程序代码的角度来看,ODBC,ISAM驱动程序以及Ms Access数据库的整个外部结构够可以统一为一个一致的编程接口。也即是说,提供给VB应用程序员的记录集对象视图同所使用的数据库格式及类型是相互独立的。即对FoxPro等数据库仍然可以使用众多的数据库存取对象变量,这就为非Access数据库的访问提供了最重要的方法。   二 、使用非Access数据库时的参数设置及配置文件的参数读取如果在VB的程序中使用了数据库的操作,将应用程序生成EXE文件或打包生成安装程序后,则必须提供一个配置 (.INI)文件,在INI文件中可以对不同类型的数据库进行设置。如果找不到这个INI文件, 将会导致不能访问数据库。通常情况下,INI文件的文件名和应用程序的名称相同,所以如果没有指明,VB的程序会在Windows子目录中去找和应用程序同名的INI文件。可以使用VB中的SetDataAccessOptions语句来设置INI文件。 SetDataAccessOptions语句的用法如下:SetDataAccessOptions 1 ,IniFileName其中IniFileName参数指明的是INI文件的带路径的文件名。值得注意的是,当应用程序找不到这个INI文件时,或在调用 OpenDataBase函数时对其Connect参数值没有设定为VB规定的标准值,如对FoxPro 2.5格式设定为了" FoxPro;"(应为" FoxPro 2.5; "),或者没有安装相应的ISAM驱动程序,则此时VB会显示一条错误信息" Not Found Installable ISAM "。通常,INI文件在应用程序分发出去以前已经生成,或者在安装时动态生成,也可以在应用程序中自己生成。 通常这种 INI文件中有" [Options]"、"[ISAM]"、" [Installed ISAMs]"、"[FoxPro ISAM]"、"[dBASE ISAM] " 、" [Paradox ISAM] "等设置段,对于一个完整的应用程序则还应有一个属于应用 程序自己的设置段如" [MyDB]”。可在其中设置DataType、Server、DataBase、 OpenOnStartup、DisplaySQL、QueryTimeOut等较为重要的数据库参数,并以此限定应用程序一般的运行环境。 Windows API接口函数在Kernel.exe动态链接库中提供了一个OSWritePrivateProfileString函数,此函数能按Windows下配置文件(.INI)的书写格式写入信息。 在通常情况下,应用程序还需要在运行时读取配置文件内相关项的参数。比如PageTimeOut(页加锁超时时限)、MaxBufferSize(缓冲区大小)、LockRetry(加锁失败时重试次数)等参数,通过对这些参数的读取对应用程序运行环境的设定、潜在错误的捕获等均会有很大的改善。 设此应用程序的配置文件为MyDB.INI,则具体过程如下:Funtion GetINIString$( Byval Fname$ ,Byval szItem$ ,Byval szDeFault$ ) ' 此自定义子函数实现INI 文件内设置段内参数的读取Dim Tmp As String,x As Integer Tmp = String( 2048,32 ) x = OSGetPrivateProfileString(Fname$,szItem$ , szDefault$,Tmp,Len(Tmp) ," MyDB.INI " ) GetINIString = Mid$( Tmp,1,x ) EndFunction以下这些函数的声明可写在模块文件内,且每个函数的声明必须在一行内Declare Function OSGetPrivateProfileString% Lib "Kernel" Alias "GetPrivateProfileString" (ByVal AppName$, ByVal KeyName$, ByVal keydefault$, ByVal ReturnString$, ByVal NumBytes As Integer, ByVal FileName$) Declare Function OSWritePrivateProfileString% Lib "Kernel" Alias "WritePrivateProfileString" (ByVal AppName$, ByVal KeyName$, ByVal keydefault$, ByVal FileName$) Declare Function OSGetWindowsDirectory% Lib "Kernel" Alias "GetWindowsDirectory" (ByVal a$, ByVal b%) Sub Form1_Load( ) Dim st As String Dim x As Integer Dim tmp As String tmp = String$( 255, 32 ) ' INI文件内为各种数据库格式指明已安装的相应ISAM驱动程序x = OSWritePrivateProfileString(" Installable ISAMS", "Paradox 3.X", "PDX110.DLL", "MyDB.INI" ) x = OSWritePrivateProfileString( "Installable ISAMS", "dBASE III", "XBS110.DLL", "MyDB.INI" ) x = OSWritePrivateProfileString( "Installable ISAMS", "dBASE IV", "XBS110.DLL", "MyDB.INI" ) x = OSWritePrivateProfileString( "Installable ISAMS", "FoxPro 2.0", "XBS110.DLL", "MyDB.INI" ) x = OSWritePrivateProfileString( "Installable ISAMS", "FoxPro 2.5", "XBS110.DLL", "MyDB.INI" ) x = OSWritePrivateProfileString( "Installable ISAMS", "Btrieve", "BTRV110.DLL", "MyDB.INI" ) x = OSWritePrivateProfileString( "dBase ISAM", "Deleted", "On", "MyDB.INI" ) ' 指明 INI文件的位置x = OSGetWindowsDirectory( tmp, 255 ) st = Mid$( tmp, 1, x ) SetDataAccessOption 1, st + "\mydb.ini" '获得INI文件一些参数 gwMaxGridRows = Val(GetINIString( " MyDB.INI " ,"MaxRows", "250" )) glQueryTimeout = Val(GetINIString( " MyDB.INI " ,"QueryTimeout", "5" )) glLoginTimeout = Val(GetINIString( " MyDB.INI " ,"LoginTimeout", "20" )) End Sub   三 、数据存取对象变量对外来数据库编程的方法及其实例在VB专业版数据库编程的三种方法中,第二种-使用数据库存取对象变量(DAO)的方法最具有功能强大、灵活的特点。 它能够在程序中存取ODBC 2.0的管理函数;可以控制多种记录集类型:Dynaset,Snapshot 及Table记录集合对象;可以存储过程和查询动作;可以存取数据库集合对象,例如 TableDefs,Fields,Indexes及QueryDefs;具有真正的事物处理能力。因而,这种方法对数据库处理的大多数情况都非常适用。 由于VB中的记录集对象与所使用的数据库格式及类型是相互独立的,所以在非Access数据库中也可以使用数据库存取对象变量的方法。因而 对FoxPro等外来数据库而言,使用数据库存取对象变量的方法同样也是一种最佳的选择。 有一点需要注意的是,VB的标准版中仅能使用数据控件(Data Control)对数据库中的记录进行访问,主要的数据库存取对象中也仅有Database、Dynaset对象可通过数据控件的属 性提供,其它的重要对象如TableDef、Field、Index、QueryDef、Snapshot、Table等均不能在VB的标准版中生成,所以使用数据存取对象变量的方法只能用VB 3.0以上的专业版。 (一)、非Access数据库的新建及库结构的修改VB专业版中的数据库存取对象变量可以分为两类,一类用于数据库结构的维护和管理,另一类用于数据的存取。其中表示数据库结构时可以使用下面的对象: DataBase、TableDef、Field、Index,以及三个集合 (Collection): TableDefs、Fields和Indexes 。每一个集合都是由若干个对象组成的,这些数据对象的集合可以完全看作是一个数组,并按数组的方法来调用。一旦数据库对象建立后,就可以用它对数据库的结构进行修改和数据处理。对于非Access数据库,大部分都是对应于一个目 录,所以可以使用VB的MkDir语句先生成一个目录,亦即新建一个数据库。而每一个非 Access数据库文件可看作是此目录下的一个数据表(Table),但实际上它们是互相独立的。 下面是新建一个FoxPro 2.5格式数据库的程序实例。 Sub CreateNew ( ) Dim Db1 As database , Td As TableDefs Dim T1 As New Tabledef , F1 As New Field , F2 As New Field , F3 As New Field Dim Ix1 As New Index Dim Path As String Const DB_TEXT = 10 , DB_INTEGER = 3 ChDir "\" Path$ = InputBox( " 请输入新路径名: ", "输入对话框" ) MkDir Path$ ' 新建一个子目录Set Db1 = OpenDatabase(Path$, True, False, "FoxPro 2.5;") Set Td = Db1.TableDefs T1.Name ="MyDB" '新建一个数据表,数据表名为MyDB F1.Name = "Name" , F1.Type = DB_TEXT , F1.Size = 20 F2.Name = "Class" , F2.Type = DB_TEXT , F2.Size = 20 F3.Name = "Grade" , F3.Type = DB_INTEGER T1.Fields.Append F1 '向数据表中添加这些字段T1.Fields.Append F2。
API之网络函数1. API之网络函数 WNetAddConnection 创建同一个网络资源的永久性连接 WNetAddConnection2 创建同一个网络资源的连接 WNetAddConnection3 创建同一个网络资源的连接 WNetCancelConnection 结束一个网络连接 WNetCancelConnection2 结束一个网络连接 WNetCloseEnum 结束一次枚举操作 WNetConnectionDialog 启动一个标准对话框,以便建立同网络资源的连接 WNetDisconnectDialog 启动一个标准对话框,以便断开同网络资源的连接 WNetEnumResource 枚举网络资源 WNetGetConnection 获取本地或已连接的一个资源的网络名称 WNetGetLastError 获取网络错误的扩展错误信息 WNetGetUniversalName 获取网络中一个文件的远程名称以及/或者UNC(统一命名规范)名称 WNetGetUser 获取一个网络资源用以连接的名字 WNetOpenEnum 启动对网络资源进行枚举的过程 2. API之消息函数 BroadcastSystemMessage 将一条系统消息广播给系统中所有的顶级窗口 GetMessagePos 取得消息队列中上一条消息处理完毕时的鼠标指针屏幕位置 GetMessageTime 取得消息队列中上一条消息处理完毕时的时间 PostMessage 将一条消息投递到指定窗口的消息队列 PostThreadMessage 将一条消息投递给应用程序 RegisterWindowMessage 获取分配给一个字串标识符的消息编号 ReplyMessage 答复一个消息 SendMessage 调用一个窗口的窗口函数,将一条消息发给那个窗口 SendMessageCallback 将一条消息发给窗口 SendMessageTimeout 向窗口发送一条消息 SendNotifyMessage 向窗口发送一条消息 3. API之文件处理函数 CloseHandle 关闭一个内核对象。其中包括文件、文件映射、进程、线程、安全和同步对象等 CompareFileTime 对比两个文件的时间 CopyFile 复制文件 CreateDirectory 创建一个新目录 CreateFile 打开和创建文件、管道、邮槽、通信服务、设备以及控制台 CreateFileMapping 创建一个新的文件映射对象 DeleteFile 删除指定文件 DeviceIoControl 对设备执行指定的操作 DosDateTimeToFileTime 将DOS日期和时间值转换成一个 win32 FILETIME 值 FileTimeToDosDateTime 将一个 win32 FILETIME 值转换成DOS日期和时间值 FileTimeToLocalFileTime 将一个FILETIME结构转换成本地时间 FileTimeToSystemTime 根据一个FILETIME结构的内容,装载一个SYSTEMTIME结构 FindClose 关闭由FindFirstFile函数创建的一个搜索句柄 FindFirstFile 根据文件名查找文件 FindNextFile 根据调用FindFirstFile函数时指定的一个文件名查找下一个文件 FlushFileBuffers 针对指定的文件句柄,刷新内部文件缓冲区 FlushViewOfFile 将写入文件映射缓冲区的所有数据都刷新到磁盘 GetBinaryType 判断文件是否可以执行 GetCompressedFileSize 判断一个压缩文件在磁盘上实际占据的字节数 GetCurrentDirectory 在一个缓冲区中装载当前目录 GetDiskFreeSpace 获取与一个磁盘的组织有关的信息,以及了解剩余空间的容量 GetDiskFreeSpaceEx 获取与一个磁盘的组织以及剩余空间容量有关的信息 GetDriveType 判断一个磁盘驱动器的类型 GetExpandedName 取得一个压缩文件的全名 GetFileAttributes 判断指定文件的属性 GetFileInformationByHandle 这个函数提供了获取文件信息的一种机制 GetFileSize 判断文件长度 GetFileTime 取得指定文件的时间信息 GetFileType 在给出文件句柄的前提下,判断文件类型 GetFileVersionInfo 从支持版本标记的一个模块里获取文件版本信息
要改协议,,高手帮下忙。。在线等。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Messaging;
using System.Net.Sockets;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading ;
using System.Net;

namespace GprsServer
{
///
/// Form1 的摘要说明。
///

public class GprsServer : System.Windows.Forms.Form
{
///
/// 必需的设计器变量。
///


[DllImport("User32.dll",EntryPoint="SendMessage")]
private static extern int
SendMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
string lParam // second message parameter
);
[DllImport("User32.dll",EntryPoint="FindWindow")]
private static extern int FindWindow(string lpClassName,string lpWindowName);

[DllImport("kernel32.dll")]
public static extern int GetPrivateProfileString ( string section ,string key , string def , StringBuilder retVal ,int size , string filePath ) ;
[DllImport("kernel32")]
public static extern long WritePrivateProfileString ( string section,string key,string val,string filePath ) ;

private System.ComponentModel.IContainer components;

public static int LocaPort;//本地端口
public static string RemoteIp;
public static int RemotePort;//远程端口
public static string sCompanyName;//公司名称

private Icon m_Icon1;
private Icon m_Icon2;
private Icon m_Icon3;

private NotifyIcon notifyIcon;

MenuItem menuItem1;
MenuItem menuItem2;

private Hashtable CarID_RemoteIP_Hash;

private Thread thGprs ;
private Thread thTcpMsg ;
private Socket socket;
private Socket TcpSocket;

private System.Windows.Forms.Timer TimerIcon;
private System.Windows.Forms.Label lblInfo;
private System.Windows.Forms.Timer TimerConn;
private byte[] TempBuff;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.ImageList imgList;// = new byte[1024];
private byte[] TcpBuff;
private System.Windows.Forms.ListView lvwMsg;
private System.Windows.Forms.ColumnHeader sId;
private System.Windows.Forms.ColumnHeader sNote;
private System.Windows.Forms.Button cmdExit;
private System.Windows.Forms.Button cmdSet;// = new byte[2048];

private bool bTsFlag=false;
public GprsServer()
{

InitializeComponent();
//检测配置文件目录是否存在
GetSysPra();

TempBuff= new byte[1];
TcpBuff=new byte[1];

m_Icon1 = new Icon("SysFile\\Icon1.ico");
m_Icon2 = new Icon("SysFile\\Icon2.ico");
m_Icon3 = new Icon("SysFile\\Icon3.ico");

notifyIcon = new NotifyIcon();
notifyIcon.Icon = m_Icon1;
notifyIcon.Text = sCompanyName;
notifyIcon.Visible = true;

menuItem1=new MenuItem("设置");
menuItem2=new MenuItem("退出");

menuItem1.Click+=new EventHandler(this.menuItem1_Click);
menuItem2.Click+=new EventHandler(this.menuItem2_Click);

notifyIcon.ContextMenu=new ContextMenu(new MenuItem[]{menuItem1,menuItem2});
notifyIcon.DoubleClick+=new System.EventHandler(this.notifyIcon_DBClick);

CarID_RemoteIP_Hash=new Hashtable();

thGprs = new Thread(new ThreadStart(ReadUdp)) ;
//启动线程
thGprs.IsBackground =true;//将线程作为后台线程处理,用途,当主线程关闭,子线程随着关闭
thGprs.Start( );

try
{
IPHostEntry IPHost = Dns.Resolve(RemoteIp);
string []aliases = IPHost.Aliases;
IPAddress []addr = IPHost.AddressList;
EndPoint ep = new IPEndPoint(addr[0],RemotePort);
TcpSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
TcpSocket.Connect(ep);

thTcpMsg = new Thread (new ThreadStart(ReadTcpMsg)) ;
//启动线程
thTcpMsg.IsBackground =true;
thTcpMsg.Start( ) ;
lblInfo.Text ="系统运行正常,正在中转GPRS数据...";
}
catch
{}
}

private void GetSysPra()
{
StringBuilder temp = new StringBuilder(255);
if (Directory.Exists("SysIni"))
{
if (File.Exists("SysIni\\SysIni.ini"))
{
int i;
i= GetPrivateProfileString("PortIni","UdpPort","",temp,255,"SysIni\\SysIni.ini");
if (i==0)
{
LocaPort=8888;
WritePrivateProfileString("PortIni","UdpPort","8888","SysIni\\SysIni.ini");
}
else
{
LocaPort=int.Parse(temp.ToString( ));
}
i = GetPrivateProfileString("Company","Name","",temp,255,"SysIni\\SysIni.ini");
if (i==0)
{
sCompanyName="龙翰科技";
WritePrivateProfileString("Company","Name","龙翰科技","SysIni\\SysIni.ini");
}
else
{
sCompanyName=temp.ToString( );
}
i = GetPrivateProfileString("PortIni","TcpAddress","",temp,255,"SysIni\\SysIni.ini");
if (i==0)
{
RemoteIp="127.0.0.1";
WritePrivateProfileString("PortIni","TcpAddress","127.0.0.1","SysIni\\SysIni.ini");
}
else
{
RemoteIp=temp.ToString( );
}
i = GetPrivateProfileString("PortIni","TcpPort","",temp,255,"SysIni\\SysIni.ini");
if (i==0)
{
RemotePort=6666;
WritePrivateProfileString("PortIni","TcpPort","6666","SysIni\\SysIni.ini");
}
else
{
RemotePort=int.Parse(temp.ToString( ));
}
}
else
{
//File.Create("SysIni\\SysIni.ini",255);
LocaPort=8888;
WritePrivateProfileString("PortIni","UdpPort","8888","SysIni\\SysIni.ini");
sCompanyName="龙翰科技";
WritePrivateProfileString("Company","Name","龙翰科技","SysIni\\SysIni.ini");
RemoteIp="127.0.0.1";
WritePrivateProfileString("PortIni","TcpAddress","127.0.0.1","SysIni\\SysIni.ini");
RemotePort=6666;
WritePrivateProfileString("PortIni","TcpPort","6666","SysIni\\SysIni.ini");
}
}
else
{
Directory.CreateDirectory("SysIni");
//File.Create("SysIni\\SysIni.ini",255);
LocaPort=8888;
WritePrivateProfileString("PortIni","UdpPort","8888","SysIni\\SysIni.ini");
sCompanyName="龙翰科技";
WritePrivateProfileString("Company","Name","龙翰科技","SysIni\\SysIni.ini");
RemoteIp="127.0.0.1";
WritePrivateProfileString("PortIni","TcpAddress","127.0.0.1","SysIni\\SysIni.ini");
RemotePort=6666;
WritePrivateProfileString("PortIni","TcpPort","6666","SysIni\\SysIni.ini");
}
}
///
/// 清理所有正在使用的资源。
///


private void menuItem1_Click(object sender,System.EventArgs e)
{
//
}
private void menuItem2_Click(object sender,System.EventArgs e)
{
this.Close();
Application.Exit();
}
private void notifyIcon_DBClick(object sender, System.EventArgs e)
{
//
}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
notifyIcon.Visible =false;;
notifyIcon.Icon=null;
notifyIcon.Dispose();
m_Icon1.Dispose();
m_Icon2.Dispose();
m_Icon3.Dispose();
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
///
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///

private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(GprsServer));
this.TimerIcon = new System.Windows.Forms.Timer(this.components);
this.lblInfo = new System.Windows.Forms.Label();
this.TimerConn = new System.Windows.Forms.Timer(this.components);
this.lvwMsg = new System.Windows.Forms.ListView();
this.sId = new System.Windows.Forms.ColumnHeader();
this.sNote = new System.Windows.Forms.ColumnHeader();
this.imgList = new System.Windows.Forms.ImageList(this.components);
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.cmdExit = new System.Windows.Forms.Button();
this.cmdSet = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// TimerIcon
//
this.TimerIcon.Enabled = true;
this.TimerIcon.Interval = 1000;
this.TimerIcon.Tick += new System.EventHandler(this.TimerIcon_Tick);
//
// lblInfo
//
this.lblInfo.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblInfo.Location = new System.Drawing.Point(4, 298);
this.lblInfo.Name = "lblInfo";
this.lblInfo.Size = new System.Drawing.Size(310, 23);
this.lblInfo.TabIndex = 0;
this.lblInfo.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// TimerConn
//
this.TimerConn.Enabled = true;
this.TimerConn.Interval = 6000;
this.TimerConn.Tick += new System.EventHandler(this.TimerConn_Tick);
//
// lvwMsg
//
this.lvwMsg.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.sId,
this.sNote});
this.lvwMsg.FullRowSelect = true;
this.lvwMsg.Location = new System.Drawing.Point(2, 2);
this.lvwMsg.Name = "lvwMsg";
this.lvwMsg.Size = new System.Drawing.Size(564, 292);
this.lvwMsg.SmallImageList = this.imgList;
this.lvwMsg.TabIndex = 1;
this.lvwMsg.View = System.Windows.Forms.View.Details;
//
// sId
//
this.sId.Text = "";
this.sId.Width = 21;
//
// sNote
//
this.sNote.Text = "消息内容";
this.sNote.Width = 522;
//
// imgList
//
this.imgList.ColorDepth = System.Windows.Forms.ColorDepth.Depth16Bit;
this.imgList.ImageSize = new System.Drawing.Size(16, 16);
this.imgList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgList.ImageStream")));
this.imgList.TransparentColor = System.Drawing.Color.Transparent;
//
// checkBox1
//
this.checkBox1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.checkBox1.Location = new System.Drawing.Point(332, 300);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(104, 19);
this.checkBox1.TabIndex = 2;
this.checkBox1.Text = "显示调试数据";
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
//
// cmdExit
//
this.cmdExit.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.cmdExit.Location = new System.Drawing.Point(504, 298);
this.cmdExit.Name = "cmdExit";
this.cmdExit.Size = new System.Drawing.Size(60, 22);
this.cmdExit.TabIndex = 3;
this.cmdExit.Text = "退出(&E)";
this.cmdExit.Click += new System.EventHandler(this.cmdExit_Click);
//
// cmdSet
//
this.cmdSet.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.cmdSet.Location = new System.Drawing.Point(432, 298);
this.cmdSet.Name = "cmdSet";
this.cmdSet.Size = new System.Drawing.Size(60, 22);
this.cmdSet.TabIndex = 4;
this.cmdSet.Text = "设置(&S)";
this.cmdSet.Click += new System.EventHandler(this.cmdSet_Click);
//
// GprsServer
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(566, 323);
this.Controls.Add(this.cmdSet);
this.Controls.Add(this.cmdExit);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.lvwMsg);
this.Controls.Add(this.lblInfo);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "GprsServer";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "中继服务器";
this.Load += new System.EventHandler(this.GprsServer_Load);
this.ResumeLayout(false);

}
#endregion

///
/// 应用程序的主入口点。
///

[STAThread]
static void Main()
{
Application.Run(new GprsServer());
}

private byte Get_CheckXor(ref byte[] temp,int len)
{
byte A=0;
for(int i=0;i {
A^=temp[i];
}
return A;
}

private void ReadTcpMsg() //读取用户发送的指令数据
{
byte[] buff= new byte[2048];
string CartIpAddress="";//车辆的IP地址
EndPoint TempRemote = null;

int recv = 0;
byte[] Tbuff;
byte[] AllBuff;
int iLenght=0;
int iIndex=0;
int iLen=0;
int iXorValue=0;

while(true)
{
try
{
recv=TcpSocket.Receive(buff,0,TcpSocket.Available,SocketFlags.None);//读取数据内容
if (recv==0)
{
recv=TcpSocket.Receive(buff,0,TcpSocket.Available,SocketFlags.None);//读取数据内容
if (recv==0)
{
TcpSocket.Close();
break;
}
}

}
catch
{
break;
}

AllBuff=new byte[recv +TcpBuff.Length];
for (iIndex = 1; iIndex <=TcpBuff.Length; iIndex++)
{
AllBuff[iIndex-1]=TcpBuff[iIndex-1];
}

for (iIndex = 1; iIndex <=recv; iIndex++)
{
AllBuff[TcpBuff.Length+iIndex-1]=buff[iIndex-1];
}

for (iIndex = 1; iIndex <=AllBuff.Length; iIndex++)
{
iLenght=AllBuff.Length-iIndex+1;
if (iLenght<6)//检测数据包长度
{
//不完整,则将指令保存
if (iLenght>0)
{
TcpBuff=new byte[iLenght];
for (iLen = 1; iLen <=iLenght; iLen++)
{
TcpBuff[iLen-1]=AllBuff[iLen+iIndex-2];
}
}
break;
}
else
{
//检测当前指令是否是完整的指令,查找数据包头
if (AllBuff[iIndex-1]==0x29 & AllBuff[iIndex]==0x29)
{
if ((AllBuff.Length -iIndex)>=(AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+4))
{
//检测当前指令是否是完整的指令
if ((AllBuff[AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+iIndex+3])==0x0D)
{
//在接收的数据中获取单条完整的指令数据
Tbuff=new byte[AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+5];
for (iLen = 1; iLen <=Tbuff.Length; iLen++)
{
Tbuff[iLen-1]=AllBuff[iLen+iIndex-2];
}
iXorValue=Get_CheckXor(ref Tbuff,Tbuff.Length-2);
if(iXorValue!=Tbuff[Tbuff.Length-2])
{
//校验不合格,继续查找合法指令数据
continue;
}
else
{
if (bTsFlag)
{
string BuffToStr="";
for(int i=0;i {
BuffToStr+=Tbuff[i].ToString("X2")+" ";
}
ShowSysMsg(BuffToStr,2);
}
//获取车载终端手机号
CartIpAddress=Tbuff[5]+"." +Tbuff[6] +"."+Tbuff[7] +"."+Tbuff[8];
TempRemote=(EndPoint)CarID_RemoteIP_Hash[CartIpAddress];
if( TempRemote==null)
{
if (bTsFlag)
{
ShowSysMsg("无法查找到接收数据的远程终节点!",3);
}
}
else
{
try
{
socket.SendTo(Tbuff,TempRemote);
if (bTsFlag)
{
ShowSysMsg("数据成功转发到车载终端!",1);
}
}
catch
{
if (bTsFlag)
{
ShowSysMsg("数据转发到车载终端失败!",3);
}
}
}
iIndex=iIndex+Tbuff.Length-1;
TcpBuff=new byte[1];
}
}
else
{
continue;
}
}
else
{
if ((AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+4)>1024)
{
continue;
}
else
{
//不完整,则将指令保存
if (iLenght>0)
{
TcpBuff=new byte[iLenght];
for (iLen = 1; iLen <=iLenght; iLen++)
{
TcpBuff[iLen-1]=AllBuff[iLen+iIndex-2];
}
break;
}
else
{
TcpBuff=new byte[1];
break;
}

}
}
}
else
{
continue;
}
}//检测数据包长度
}
}
}

public void ShowSysMsg(string sNote,int iIcon)
{
//显示系统消息
try
{
lvwMsg.BeginUpdate();
if (lvwMsg.Items.Count >100)
lvwMsg.Items.Clear();
ListViewItem li = new ListViewItem();
//li.SubItems[0].Text =sNote ;
li.SubItems.Add (sNote);
li.ImageIndex=iIcon;
lvwMsg.Items.Add(li);
lvwMsg.EndUpdate();
}
catch
{}
}

private void ReadUdp() //从UDP数据端口读取GPRS数据
{
byte[] buff = new byte[1024];
int recv = 0;
byte[] Tbuff;
byte[] AllBuff;
int iLenght=0;
int iIndex=0;
int iLen=0;
int iXorValue=0;
string CarIpAddress="";
byte[] RecvAffirmBuff=new byte[]{0x29,0x29,0x21,0x00,0x05,0,0,0,0,0x0D};//回应终端数组

IPEndPoint ipep = new IPEndPoint(IPAddress.Any ,LocaPort);
//socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
socket.Bind(ipep);
ShowSysMsg("系统成功在"+LocaPort + "端口侦听!",6);
}
catch
{
ShowSysMsg("端口"+LocaPort+"已被占用,系统侦听失败!",5);
return;
}
IPEndPoint sender = new IPEndPoint(IPAddress.Any , 0);//指远程终端(终节点)Ip地址对象 IPAddress.Any表示任何地址 0 表示任何端口
EndPoint remote = (EndPoint)(sender); //指远程终端(终节点)

while(true)
{
try
{
recv = socket.ReceiveFrom(buff , ref remote);
}
catch
{
ShowSysMsg("接收车载终端数据错误!",3);
}
//---------------------you2004-12-31 begin------------------------------//
AllBuff=new byte[recv +TempBuff.Length];
for (iIndex = 1; iIndex <=TempBuff.Length; iIndex++)
{
AllBuff[iIndex-1]=TempBuff[iIndex-1];
}

for (iIndex = 1; iIndex <=recv; iIndex++)
{
AllBuff[TempBuff.Length+iIndex-1]=buff[iIndex-1];
}

for (iIndex = 1; iIndex <=AllBuff.Length; iIndex++)
{
iLenght=AllBuff.Length-iIndex+1;
if (iLenght<6)//检测数据包长度
{
//不完整,则将指令保存
if (iLenght>0)
{
TempBuff=new byte[iLenght];
for (iLen = 1; iLen <=iLenght; iLen++)
{
TempBuff[iLen-1]=AllBuff[iLen+iIndex-2];
}
}
break;
}
else
{
//检测当前指令是否是完整的指令,查找数据包头
if (AllBuff[iIndex-1]==0x29 & AllBuff[iIndex]==0x29)
{
if ((AllBuff.Length -iIndex)>=(AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+4))
{
//检测当前指令是否是完整的指令
if ((AllBuff[AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+iIndex+3])==0x0D)
{
//在接收的数据中获取单条完整的指令数据
Tbuff=new byte[AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+5];
for (iLen = 1; iLen <=Tbuff.Length; iLen++)
{
Tbuff[iLen-1]=AllBuff[iLen+iIndex-2];
}
iXorValue=Get_CheckXor(ref Tbuff,Tbuff.Length-2);
if(iXorValue!=Tbuff[Tbuff.Length-2])
{
//校验不合格,继续查找合法指令数据
continue;
}
else
{
if (bTsFlag)
{
string BuffToStr="";
for(int i=0;i {
BuffToStr+=Tbuff[i].ToString("X2")+" ";
}
ShowSysMsg(BuffToStr,0);
}

//获取车载终端手机号
CarIpAddress=Tbuff[5]+"." +Tbuff[6] +"."+Tbuff[7] +"."+Tbuff[8];

//-----------------检测系统哈希表是否包含此终端数据---------------------\\
if(CarID_RemoteIP_Hash.ContainsKey(CarIpAddress))
{
CarID_RemoteIP_Hash[CarIpAddress]=remote;//有更新
}
else
{
CarID_RemoteIP_Hash.Add(CarIpAddress,remote);//没有添加
}

//--------------------将数据转发到中心处理程序-----------------\\
if (TcpSocket.Connected)
{
try
{
TcpSocket.Send(Tbuff,0,Tbuff.Length,SocketFlags.None);
if (bTsFlag)
{
ShowSysMsg("数据成功转发到网络中心处理程序!",1);
}
}
catch
{
if (bTsFlag)
{
ShowSysMsg("数据转发到网络中心处理程序失败!",3);
}
}
}
//-------------------向终端发出0x21的接收确认-------------------\\
RecvAffirmBuff[5]=Tbuff[Tbuff.Length-2];
RecvAffirmBuff[6]=Tbuff[2];
RecvAffirmBuff[7]=Tbuff[9];
RecvAffirmBuff[8]=Get_CheckXor(ref RecvAffirmBuff,8);
socket.SendTo(RecvAffirmBuff,remote);
iIndex=iIndex+Tbuff.Length-1;
TempBuff=new byte[1];
}
}
else
{
continue;
}
}
else
{
if ((AllBuff[iIndex+2]*256+ AllBuff[iIndex+3]+4)>1024)
{
continue;
}
else
{
//不完整,则将指令保存
if (iLenght>0)
{
TempBuff=new byte[iLenght];
for (iLen = 1; iLen <=iLenght; iLen++)
{
TempBuff[iLen-1]=AllBuff[iLen+iIndex-2];
}
break;
}
else
{
TempBuff=new byte[1];
break;
}

}
}
}
else
{
continue;
}
}//检测数据包长度

}
//---------------------you2004-12-31 end------------------------------//
}

}

private void GprsServer_Load(object sender, System.EventArgs e)
{
//
}

int I=0;
private void TimerIcon_Tick(object sender, System.EventArgs e)
{
if(thGprs!=null)
{
if(thGprs.IsAlive)
notifyIcon.Icon=notifyIcon.Icon==m_Icon1?m_Icon2:m_Icon1;
else
notifyIcon.Icon=notifyIcon.Icon==m_Icon1?m_Icon3:m_Icon1;
}
I++;
if(I>5)
{
I=FindWindow(null,@sCompanyName);
if( I!= 0)
{
SendMessage(I,0x501,1002,"");
}
I=0;
}
}

private void TimerConn_Tick(object sender, System.EventArgs e)
{
if (!TcpSocket.Connected)
{
try
{
lblInfo.Text ="与中心数据处理程序断开,正在进行二次连接...";
IPHostEntry IPHost = Dns.Resolve(RemoteIp);
string []aliases = IPHost.Aliases;
IPAddress []addr = IPHost.AddressList;
EndPoint ep = new IPEndPoint(addr[0],RemotePort);
TcpSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
TcpSocket.Connect(ep);

thTcpMsg = new Thread ( new ThreadStart(ReadTcpMsg)) ;
//启动线程
thTcpMsg.IsBackground =true;
thTcpMsg.Start( ) ;
lblInfo.Text ="系统运行正常,正在中转GPRS数据...";
}
catch
{
return;
}
}
}

private void checkBox1_CheckedChanged(object sender, System.EventArgs e)
{
bTsFlag=checkBox1.Checked;
}

private void cmdExit_Click(object sender, System.EventArgs e)
{
if(MessageBox.Show("确定关闭中继服务器?", "提示",MessageBoxButtons.YesNo,MessageBoxIcon.Information) == DialogResult.Yes)
{
Application.Exit ();
}
}

private void cmdSet_Click(object sender, System.EventArgs e)
{
frmUdpSet frmudpset=new frmUdpSet();
frmudpset.Show();
}

protected override void OnClosing(CancelEventArgs e)
{
e.Cancel =true;
this.WindowState =FormWindowState.Minimized;
}
}
}

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧