📄 socketserver.java
字号:
package socket;import javax.microedition.midlet.*;import javax.microedition.io.*;import javax.microedition.lcdui.*;import java.io.*;public class SocketServer extends MIDlet implements Runnable, CommandListener { private Display display; private Form f; private TextField tf; // 用于要输入发送的字符串 private StringItem si; // 用于显示接收到的字符串 private Command sendCommand = new Command("Send", Command.ITEM, 1); private Command exitCommand = new Command("Exit", Command.EXIT, 1); SocketConnection sc; // 套接字连接 ServerSocketConnection scn; // 服务器端套接字连接 InputStream is; // 输入流 OutputStream os; // 输出流 Sender sender; // 用于发送数据的线程 public SocketServer() { display = Display.getDisplay(this); f = new Form("Socket Server"); tf = new TextField("发送:", "", 30, TextField.ANY); si = new StringItem("状态:", " "); f.append(tf); f.append(si); f.addCommand(exitCommand); f.setCommandListener(this); display.setCurrent(f); } public void startApp() { new Thread(this).start(); // 开始服务器端连接的线程 } public void run() { try { si.setText("等待连接……"); // 设置当前显示的状态 // 在5000端口建立服务器端套接字 scn = (ServerSocketConnection) Connector.open("socket://:5000"); // 等待连接,连接后返回连接的套接字对象 sc = (SocketConnection) scn.acceptAndOpen(); si.setText("接受连接"); // 设置当前显示的状态 is = sc.openInputStream(); // 打开输入流 os = sc.openOutputStream(); // 打开输出流 sender = new Sender(os); // 建立线程,用于发送数据 f.addCommand(sendCommand); // 只有当连接建立后才允许发送数据 while (true) { // 永久循环,用于接收数据并显示 StringBuffer sb = new StringBuffer(); int c = 0; while (((c = is.read()) != '\n') && (c != -1)) { sb.append((char) c); } if (c == -1) break; // 输入流关闭,跳出循环 si.setText("接收到消息 - " + sb.toString()); // 显示接收到的数据 } stop(); // 关闭输入/输出流和Socket连接 si.setText("连接关闭"); // 设置当前显示的状态 f.removeCommand(sendCommand); } catch (Exception e) { if (e.getMessage().equals("ServerSocket Open")) { System.out.println("错误:端口5000已经被占用"); destroyApp(true); notifyDestroyed(); } else System.out.println("错误:"+e.getMessage()); } } public void pauseApp() { } public void destroyApp(boolean unconditional) { stop(); } public void commandAction(Command c, Displayable s) { if (c == exitCommand) { destroyApp(true); notifyDestroyed(); } else if (c == sendCommand) { sender.send(tf.getString()); // 将输入的字符串发送 } } // 关闭输入/输出流和Socket连接 public void stop() { try { if (sender != null) sender.stop(); if (is != null) is.close(); if (os != null) os.close(); if (sc != null) sc.close(); if (scn != null) scn.close(); } catch (IOException ioe) { } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -