使用Socket 是连接两台计算机最简单的方法,另外由于Socket 使用的是TCP 协议,所以也就保证了传输的质量。但在这里要注意的是,并不是所有的MIDP 设备都支持Socket 网络。在这部分中我们主要涉及到的两个接口是SocketConnection 和ServerSocketConnection。这个两个接口的使用方法其实和J2SE 中的Socket 和ServerSocket 类的使用方法很相似。不同的是ServerSocketConnection 中打开一个SocketConnection 作为监听者的方法是acceptAndOpen()。同时你可以用getLocalAddress()和getLocalPort()两个方法获得本地的绑定IP 地址和所打开的端口号,这样你就可以告诉另外一台MIDP 设备你所使用的IP 和端口,使得另一台MIDP 设备可以连接到你的设备上。在这里我们除了强调使用acceptAndOpen()从一个ServerSocketConnection 对象中打开一个SocketConnection 作为监听者外,还要说明的是作为套接字我们是可以设置一些属性的,这些属性的设置是通过SocketConnection.setSocketOption()方法来设置
package socketText; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.microedition.io.Connector; import javax.microedition.io.ServerSocketConnection; import javax.microedition.io.SocketConnection; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.StringItem; import javax.microedition.lcdui.TextField; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; /** */ /** * * @author leilu 服务器端代码 */ public class SocketServer extends MIDlet implements CommandListener, Runnable ... { private Display display; private Form f; private StringItem si; private TextField tf; private boolean stop; // 创建Command对象 private Command sendCommand = new Command("send", Command.ITEM, 1); private Command exitCommand = new Command("Exit", Command.EXIT, 1); // 输入流 InputStream is; // 输出流 OutputStream os; // Socket连接 SocketConnection sc; // Socket服务器连接 ServerSocketConnection scn; public SocketServer() ...{ display = Display.getDisplay(this); f = new Form("Socket Server"); si = new StringItem("Status:", " "); // 显示发送消息的控件 tf = new TextField("Send:", "", 30, TextField.ANY); f.append(si); f.append(tf); f.addCommand(exitCommand); // f.addCommand(sendCommand); f.setCommandListener(this); display.setCurrent(f); // 启动线程 Thread t = new Thread(this); t.start(); } protected void startApp() throws MIDletStateChangeException ...{ // TODO Auto-generated method stub } protected void pauseApp() ...{ // TODO Auto-generated method stub } protected void destroyApp(boolean arg0) throws MIDletStateChangeException ...{ // TODO Auto-generated method stub } public void commandAction(Command c, Displayable d) ...{ if (sendCommand == c) ...{ try ...{ os.write(tf.getString().getBytes()); os.write(" ".getBytes()); } catch (IOException e) ...{ // TODO Auto-generated catch block e.printStackTrace(); } } else if (exitCommand == c) ...{ try ...{ destroyApp(false); this.notifyDestroyed(); } catch (MIDletStateChangeException e) ...{ // TODO Auto-generated catch block e.printStackTrace(); } } } public void run() ...{ si.setText("Waiting for connection"); // 创建一个服务器的ServerSocketConnection连接 try ...{ scn = (ServerSocketConnection) Connector.open("socket://:5000"); // 等待一个连接 sc = (SocketConnection) scn.acceptAndOpen(); // 设置提示信息 si.setText("Connection accepted"); is = sc.openInputStream(); os = sc.openOutputStream(); // 连接完成后允许发送 f.addCommand(sendCommand); // 读取客户端发来的消息 while (true) ...{ StringBuffer sb = new StringBuffer(); int c = 0; // 读取数据 while (((c = is.read()) != ' ') && (c != -1)) ...{ sb.append((char) c); } // 如果读取数据失败 if (c == -1) ...{ break; } // 显示客户端反发送过来的消息 si.setText("Message receved-" + sb.toString()); } si.setText("Connection is closed"); // 连接结束,则不实现发送按钮 f.removeCommand(sendCommand); } catch (IOException ioe) ...{ if (ioe.getMessage().equals("ServerSocket Open")) ...{ // 提示端口己经被占用 Alert a = new Alert("Server", "Port 5000 is already taken.", null, AlertType.ERROR); a.setTimeout(Alert.FOREVER); a.setCommandListener(this); display.setCurrent(a); } else ...{ if (!stop) ...{ ioe.printStackTrace(); } } } catch (Exception e) ...{ e.printStackTrace(); } } // 释放资源 public void stop() ...{ try ...{ stop = true; if (is != null) ...{ is.close(); } if (os != null) ...{ os.close(); } if (sc != null) ...{ sc.close(); } if (scn != null) ...{ scn.close(); } } catch (IOException e) ...{ // TODO Auto-generated catch block e.printStackTrace(); } }}
package socketText; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.microedition.io.ConnectionNotFoundException; import javax.microedition.io.Connector; import javax.microedition.io.SocketConnection; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.StringItem; import javax.microedition.lcdui.TextField; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class SocketClient extends MIDlet implements Runnable, CommandListener ... { private Display display; private Form f; private StringItem si; private TextField tf; private boolean stop; // 创建Command对象 private Command sendCommand = new Command("send", Command.ITEM, 1); private Command exitCommand = new Command("Exit", Command.EXIT, 1); // 输入流 InputStream is; // 输出流 OutputStream os; // Socket连接 SocketConnection sc; public SocketClient() ...{ display = Display.getDisplay(this); f = new Form("Socket Server"); si = new StringItem("Status:", " "); // 显示发送消息的控件 tf = new TextField("Send:", "", 30, TextField.ANY); f.append(si); f.append(tf); f.addCommand(exitCommand); f.addCommand(sendCommand); f.setCommandListener(this); display.setCurrent(f); // 启动线程 Thread t = new Thread(this); t.start(); } protected void startApp() throws MIDletStateChangeException ...{ // TODO Auto-generated method stub } protected void pauseApp() ...{ // TODO Auto-generated method stub } protected void destroyApp(boolean arg0) throws MIDletStateChangeException ...{ // TODO Auto-generated method stub } public void run() ...{ try ...{ // 打开一个连接本地服务器的SocketConnection sc = (SocketConnection) Connector.open("socket://localhost:5000"); si.setText("Connected to server"); // 设置提示信息 si.setText("Connection accepted"); is = sc.openInputStream(); os = sc.openOutputStream(); // 读取服务器端发来的消息 while (true) ...{ StringBuffer sb = new StringBuffer(); int c = 0; // 读取数据 while (((c = is.read()) != ' ') && (c != -1)) ...{ sb.append((char) c); } // 如果读取数据失败 if (c == -1) ...{ break; } // 显示消息 si.setText("Message receved-" + sb.toString()); } // 停止连接 stop(); si.setText("Connection is closed"); // 连接结束,则不实现发送按钮 f.removeCommand(sendCommand); } catch (ConnectionNotFoundException cnf) ...{ // 提示端口己经被占用 Alert a = new Alert("Client", "please run server first.", null, AlertType.ERROR); a.setTimeout(Alert.FOREVER); a.setCommandListener(this); display.setCurrent(a); } catch(IOException ioe) ...{ if (!stop) ...{ ioe.printStackTrace(); } } catch (Exception e) ...{ e.printStackTrace(); } } public void commandAction(Command c, Displayable d) ...{ if (sendCommand == c) ...{ try ...{ os.write(tf.getString().getBytes()); os.write(" ".getBytes()); } catch (IOException e) ...{ // TODO Auto-generated catch block e.printStackTrace(); } } else if (exitCommand == c) ...{ try ...{ destroyApp(false); this.notifyDestroyed(); } catch (MIDletStateChangeException e) ...{ // TODO Auto-generated catch block e.printStackTrace(); } } } public void stop() ...{ try ...{ stop = true; if (is != null) ...{ is.close(); } if (os != null) ...{ os.close(); } if (sc != null) ...{ sc.close(); } } catch (IOException e) ...{ // TODO Auto-generated catch block e.printStackTrace(); } }}