以下是两个程序,我希望把前一个程序(OPC客户端)的读数功能整合在另一个程序(通信服务器)里,无从下手,清高手指点!!!
OPC客户端:
public bool CreateGroup()
{
try
{
// add our only working group
theGrp = theSrv.AddGroup( "OPCdotNET-Group", true, 500 );
// add event handler for data changes
theGrp.DataChanged += new DataChangeEventHandler( this.theGrp_DataChange );
theGrp.WriteCompleted += new WriteCompleteEventHandler( this.theGrp_WriteComplete );
}
catch( COMException )
{
MessageBox.Show( this, "create group error!", "Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning );
return false;
}
return true;
}
// event handler: called if any item in group has changed values
protected void theGrp_DataChange( object sender, DataChangeEventArgs e )
{
Trace.WriteLine( "theGrp_DataChange id=" + e.transactionID.ToString() + " me=0x" + e.masterError.ToString( "X" ) );
foreach( OPCItemState s in e.sts )
{
if( s.HandleClient != itmHandleClient ) // only one client handle
continue;
Trace.WriteLine( " item error=0x" + s.Error.ToString( "X" ) );
if( HRESULTS.Succeeded( s.Error ) )
{
Trace.WriteLine( " val=" + s.DataValue.ToString() );
txtItemValue.Text = s.DataValue.ToString(); // update screen
txtItemQual.Text = OpcGroup.QualityToString( s.Quality );
txtItemTimeSt.Text = DateTime.FromFileTime( s.TimeStamp ).ToString();
}
else
{
txtItemValue.Text = "ERROR 0x" + s.Error.ToString( "X" );
txtItemQual.Text = "error";
txtItemTimeSt.Text = "error";
}
}
}
通信服务器端:
public class SynchronousSocketListener
{
// 从客户端输入的数据
public static string data = null;
public static void StartListening()
{
// 为输入数据提供的数据缓存
byte[] bytes = new Byte[1024];
// 为套接字建立本地端口
// Dns.获得主机名称返回主机运行申请的名称
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// 创建一个TCP/IP套接字
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// 将套接字绑定在本地端口并监听输入的连接
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// 开始监听连接
while (true)
{
Console.WriteLine("等待连接中...");
// 当等待一个输入的连接时程序暂停
Socket handler = listener.Accept();
data = null;
// 一个输入的连接需要被处理
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// 在控制台显示数据
Console.WriteLine("文件已接收 : {0}", data);
// 在客户端回应数据
byte[] s = Encoding.ASCII.GetBytes(data);
handler.Send(s);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n按回车键继续...");
Console.Read();
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}