我遇到使用TCPClient进行读写操作的问题。我能够连接到服务器,我得到服务器第一个响应,这是一个身份验证消息。然后,我向服务器写入所需的响应,但是,我没有收到服务器的响应。问题是,我做错了什么我阻止了阅读的反应。
static void Main( string[] args )
{
var messages = MessageSeed();
TcpClient client = null;
NetworkStream stream = null;
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = xxxx;
IPAddress address = IPAddress.Parse( "xx.xx.xx.xxx" );
IPEndPoint server = new IPEndPoint( address, port );
using( client = new TcpClient() )
{
client.Connect( server );
using( stream = client.GetStream() )
{
// Buffer to store the response bytes.
Byte[] data = new Byte[ 256 ];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read( data, 0, data.Length );
responseData = System.Text.Encoding.UTF8.GetString( data, 0, bytes );
Console.WriteLine( "Received: {0}", responseData );
JTimeMessage firstResposne = new JTimeMessage( responseData );
if( firstResposne.MessageIdentifier == "AuthChallenge" )
{
//Server connection is correct. Need to authenticate
string challengString = firstResposne.KVPs[ "ChallengeString" ].ToString();
string APIKey = "SomeAPIKey";
string sharedSecret = "SomeSharedSecret";
string challengeResponseSecrete = CreateChallengeResponse( challengString, sharedSecret );
Dictionary<string, string> responseKVPs = new Dictionary<string, string>();
responseKVPs.Add( "APIKey", APIKey );
responseKVPs.Add( "ResponseString", challengeResponseSecrete );
string responseJSON = JsonConvert.SerializeObject( responseKVPs );
string challengeResponse = $"DATA ChallengeResponse {responseJSON}";
// Translate the message into ASCII and store it as a Byte array.
data = new Byte[ 256 ];
data = System.Text.Encoding.ASCII.GetBytes( challengeResponse );
if( stream.CanWrite )
Console.Write( "writeable" );
// Send the message to the connected TcpServer.
stream.Write( data, 0, data.Length );
Console.WriteLine( "Sent: {0}", challengeResponse );
// Buffer to store the response bytes.
data = new Byte[ 256 ];
// String to store the response ASCII representation.
responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 authResultBytes = stream.Read( data, 0, data.Length );
responseData = System.Text.Encoding.ASCII.GetString( data, 0, authResultBytes );
Console.WriteLine( "Received: {0}", responseData );
}
}
}
}
catch( ArgumentNullException e )
{
Console.WriteLine( "ArgumentNullException: {0}", e );
}
catch( SocketException e )
{
Console.WriteLine( "SocketException: {0}", e );
}
finally
{
// Close everything.
stream.Close();
client.Close();
}