我有一个连接到软件的dll,我们称它为driver1。我有一个java程序,它必须连接到driver1并查询其状态。dll提供了连接和查询状态的功能。
我写了一个c++程序,我给了dll作为参考,我能够使用它的dll。我可以连接到driver1并查询它的状态。然后,我创建了一个TcpListener,我的Java程序可以作为客户机连接它。我只是简单地接受客户端在c++和等待从Java程序接收数据。
我从Java端发送数据(例如一个表示dll的"connect"方法的命令)。该命令可以很好地从c++端接收,并解析和调用dll中的指定函数。然而,当我想将dll函数的返回值写入NetworkStream以将返回值发送到Java端时,我得到一个异常说:
c++代码类似于msdn站点的TcpListener示例:先。IOException: IOException:无法向传输连接写入数据。在非套接字上尝试操作。
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;
using namespace System::Threading;
void main()
{
try
{
// Set the TcpListener on port 1124.
Int32 port = 1124;
IPAddress^ localAddr = IPAddress::Parse( "127.0.0.1" );
// TcpListener* server = new TcpListener(port);
TcpListener^ server = gcnew TcpListener( localAddr,port );
// Start listening for client requests.
server->Start();
// Buffer for reading data
array<Byte>^bytes = gcnew array<Byte>(256);
String^ data = nullptr;
Console::Write( "Waiting for a connection... " );
// Perform a blocking call to accept requests.
TcpClient^ client = server->AcceptTcpClient();
Console::WriteLine( "Connected!" );
data = nullptr;
while(true)
{
// Get a stream Object* for reading and writing
NetworkStream^ stream = client->GetStream();
Int32 i;
// Loop to receive all the data sent by the client.
while ( i = stream->Read( bytes, 0, bytes->Length ) )
{
// Translate data bytes to a ASCII String*.
data = Text::Encoding::ASCII->GetString( bytes, 0, i );
Console::WriteLine( "Received: {0}", data );
// Process the data sent by the client.
/*
*
* Here I parse the data, understand what method of the dll to call.
* Call it and make a String^ from the return value.
*
*
*/
array<Byte>^msg = Text::Encoding::ASCII->GetBytes( returnValue );
// Send back a response.
stream->Write( msg, 0, msg->Length );
Console::WriteLine( "Sent: {0}", data );
}
}
// Shutdown and end connection
client->Close();
}
catch ( SocketException^ e )
{
Console::WriteLine( "SocketException: {0}", e );
}
Console::WriteLine( "nHit enter to continue..." );
Console::Read();
}
我在调用
的那一行得到异常流->写()
你知道发生了什么吗?
我怀疑由于某种原因连接正在终止。我认为,如果您使用DOS命令NETSTAT -A
检查连接的状态,您会发现连接要么关闭,要么处于挂起状态。很难说是连接的哪一端(客户端还是服务器端)产生了问题。
另外,在发送数据之前,尝试调试TCPSocket
以检查它的状态。可能是一端过早关闭连接....