⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 socketscreen.java

📁 手机游戏设计一书的源代码
💻 JAVA
字号:
package net;

import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

/**
 *  MIDlet 显示类
 */
public class SocketScreen
    extends Form
    implements CommandListener {

  /** 构造器 */
  public SocketScreen(SocketMIDlet socketMIDlet) {
    super("Displayable Title");
    this.socketMIDlet = socketMIDlet;
    try {
      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   *组件初始化
   */
  private void jbInit() throws Exception {

    //设置当前对象为命令事件监听器
    setCommandListener(this);

    // 添加退出命令对象
    addCommand(new Command("Exit", Command.EXIT, 1));
    addCommand(new Command("Connect", Command.OK, 1));
  }

  class SocketConnector
      implements java.lang.Runnable {

    /**
     * 创建连接线程主方法
     */
    public void run() {
      connect();
    }
  }

  /**
   * 创建Socket连接主方法
   */
  public void connect() {
    byte[] buffer = new byte[128];
    try {
      SocketConnection connection = (SocketConnection) Connector.open("socket : //yourcomputer:5688");
          connection.setSocketOption(SocketConnection.LINGER, 5);
          InputStream is = connection.openInputStream();
      OutputStream os = connection.openOutputStream();
      os.write("Hello Server".getBytes());
      int ch = 0;
      int index = 0;
      while (ch != -1) {
        ch = is.read();
        if (index < 127 && ch != -1) {
          System.out.println("ch= " + ch);
          buffer[index] = (byte) ch;
        }
        else {
          break;
        }
        index++;
      }
      is.close();
      os.close();
      connection.close();
      TextBox input = new TextBox("Website content:", "", 50000, TextField.ANY);
      input.setTicker(new Ticker("connect internet"));
      StringBuffer sb = new StringBuffer();
      input.setString(new String(buffer, 0, index));
      buffer = null;
      Display.getDisplay(socketMIDlet).setCurrent(input);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  /**
   *处理命令事件方法
   */
  public void commandAction(Command command, Displayable displayable) {

    if (command.getCommandType() == Command.EXIT) {

      // 退出MIDlet
      SocketMIDlet.quitApp();

    }
    else if (command.getCommandType() == Command.OK) {

      new java.lang.Thread(new SocketConnector()).start();
    }
  }

  private SocketMIDlet socketMIDlet = null;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -