Overview
The article will demonstrate how to use the ipclient component in Secure iNet Factory
to create TCP/IP client socket connections.
Code Example
Download IpClientEx.java
01 import java.io.*;
02 import com.jscape.inet.ipclient.*;
03
04 public class IpClientEx implements IpClientListener
05 {
06 public void connected(IpClientConnectedEvent event)
07 {
08 System.out.println("Connected to host: " + event.getHostname());
09 }
10
11 public void disconnected(IpClientDisconnectedEvent event)
12 {
13 System.out.println("Disconnected from host: " + event.getHostname());
14 }
15
16 public static void main(String[] args)
17 {
18 try
19 {
20 // create new IpClient instance
21 IpClient client = new IpClient("www.yahoo.com",80);
22 // subscribe listener
23 client.addIpClientListener(new IpClientEx());
24 // establish connection
25 client.connect();
26 // get output stream
27 OutputStream out = client.getOutputStream();
28 // send data
29 String command = "GET / HTTP/1.0\r\n\r\n";
30 out.write(command.getBytes());
31 out.flush();
32 // get input stream
33 InputStream in = client.getInputStream();
34 // read data from server
35 int i = 0;
36 while((i = in.read()) != -1) System.out.print((char)i);
37 // disconnect
38 client.disconnect();
39 }
40 catch (Exception e)
41 {
42 e.printStackTrace();
43 }
44
45 }
46 }
Lines 1-2 : Necessary import statements. Lines 6-14 : Events from the attached IpClientListener. Line 21 : Create new IpClient instance. Line 23 : Add IpClientListener so this instance of IpClient can receive events. Lines 25-31 : Open the connection, issue a HTTP GET command and read the response. Lines 35-36 : Print the response to the console. Lines 38 : Disconnect from the remote server.
For a complete list of HTTP commands go here.
|
Comments