import com.sun.kjava.*; import javax.microedition.io.*; import java.io.*; /** Simple socket connection example. This Spotlet connects to * webdev.apl.jhu.edu and sends a hello. It then displays the response from * the server on the screen. * @author Robert Evans, rbevans@akane.jhuapl.edu */ public class SockTest extends Spotlet { // the graphics context Graphics g = Graphics.getGraphics(); // our exit buttons static Button exitButton; // the streams we will be using InputStream is; OutputStream os; StreamConnection socket = null; // A single stringbuffer to collect the message from the server StringBuffer stringFromWebdev = new StringBuffer(400); // a scrolling text box to handle output BasicScrollTextBox scrollText = new BasicScrollTextBox(); /** Main method */ public static void main(String[] args) { (new SockTest()).register(NO_EVENT_OPTIONS); } /** SockTest object. Creates a scrolling text box and exit button on * the screen. Queries a server program on webdev.apl.jhu.edu on port * 1501 and then prints the response */ public SockTest() { // draw our gui components scrollText = new BasicScrollTextBox("", 5, 25, 150, 115); exitButton = new Button("Exit",139,145); g.clearScreen(); exitButton.paint(); g.drawString(" Test connection to webdev.apl.jhu.edu ", 0, 0, Graphics.INVERT); // make the connections try { // first get the socket socket = (StreamConnection)Connector.open("socket://128.220.101.101:1501", Connector.READ_WRITE, true); if (socket == null) { scrollText.addText("Couldn't open socket to 128.220.101.101:1501...\n\n"); } else { scrollText.addText("Connection is established to webdev on port 1501...\n\n"); } // update the display scrollText.paint(); // get the input and output streams is = socket.openInputStream(); scrollText.paint(); os = socket.openOutputStream(); scrollText.paint(); // send the hello message if (getFlashID() == null) { os.write(("Hello from somebody's POSE").getBytes()); } else { os.write(("Hello from Palm " + getFlashID()).getBytes()); } // and read the response from the server int b; while ( (b=is.read()) != -1) { stringFromWebdev.append((char)b); } stringFromWebdev.append('\n'); stringFromWebdev.append('\n'); // print the response to the screen scrollText.addText(stringFromWebdev.toString()); scrollText.paint(); // and close the connection scrollText.addText("Closing connection..."); socket.close(); scrollText.paint(); } catch (Exception e) { scrollText.addText( "Unable to open connection..."); scrollText.paint(); } } /** Handle pen down event on exit button */ public void penDown(int x, int y) { if (exitButton.pressed(x,y)) System.exit(0); } }