NetworkClient

By: aathishankaran Viewed: 153166 times    

NetworkClient

 

This article contains the code for the network client as previous article. The NetworkClient class is a generic starting point for network clients and is extended by HttpClient.

 

private boolean checkHost(String host) {

try {

InetAddress.getByName(host);

return(true);

} catch(UnknownHostException uhe) {

outputArea.setText("Bogus host: " + host);

return(false);

}

}

}

 

NetworkClient.java

import java.net.*;

import java.io.*;

 

public class NetworkClient {

protected String host;

protected int port;

 

public NetworkClient(String host, int port) {

this.host = host;

this.port = port;

}

 

public void connect() {

try {

Socket client = new Socket(host, port);

handleConnection(client);

} catch(UnknownHostException uhe) {

System.out.println("Unknown host: " + host);

uhe.printStackTrace();

} catch(IOException ioe) {

System.out.println("IOException: " + ioe);

ioe.printStackTrace();

}

}

 

protected void handleConnection(Socket client)

throws IOException {

PrintWriter out =

SocketUtil.getWriter(client);

BufferedReader in =

SocketUtil.getReader(client);

out.println("Generic Network Client");

System.out.println

("Generic Network Client:\n" +

"Made connection to " + host +

" and got ’" + in.readLine() + "’ in response");

client.close();

}

public String getHost() {

return(host);

}

public int getPort() {

return(port);

}

}

Most Viewed Articles (in JSP )

Latest Articles (in JSP)

Comment on this tutorial