Java Equivalent Method to Test TCP Connection
In C# to test if UltraVNC was up and running on a local machine I would do this
public static bool TestAvailablility(int port, string responseStartsWith)
{
bool toReturn = false;
try
{
using (TcpClient client1 = new TcpClient())
{
client1.ReceiveTimeout = 10000;
client1.SendTimeout = 10000;
client1.Connect("localhost", port);
using (NetworkStream stream = client1.GetStream())
{
Byte[] response = new Byte[4096];
Int32 bytes = 0;
string serverReturnString = null;
bytes = stream.Read(response, 0, response.Length);
serverReturnString = System.Text.Encoding.ASCII.GetString(response开发者_StackOverflow社区, 0, bytes);
Console.WriteLine("TestAvailablility: serverReturnString = {0}", serverReturnString);
if (serverReturnString.StartsWith(responseStartsWith, StringComparison.OrdinalIgnoreCase))
{
toReturn = true;
}
}
}
}
catch (Exception ex) // SocketException for connect, IOException for the read.
{
Console.WriteLine("TestAvailable - Could not connect to VNC server. Exception info: ", ex);
}
return toReturn;
}
I'm new to Java so I'm hoping someone can help me with an equivalent method to preform this action.
Here's what I came up with:
FYI using Autocomplete in Eclipse + Java API you can translate C# to Java pretty easily.
public static boolean testAvailablility(int port, String responseStartsWith) {
boolean toReturn = false;
try {
Socket client1 = new Socket();
client1.setSoTimeout(10000);
client1.bind(new InetSocketAddress("localhost", port));
InputStream stream = client1.getInputStream();
byte[] response = new byte[4096];
int bytes = 0;
String serverReturnString = null;
bytes = stream.read(response, 0, response.length);
serverReturnString = String.valueOf(bytes);
System.out.println("TestAvailablility: serverReturnString = {0} " + serverReturnString);
if (serverReturnString.toLowerCase().startsWith(responseStartsWith.toLowerCase()))
toReturn = true;
} catch (Exception ex) // SocketException for connect, IOException for
// the read.
{
System.out.println("TestAvailable - Could not connect to VNC server. Exception info: ");
ex.printStackTrace();
}
return toReturn;
}
精彩评论