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

📄 socketclient.java

📁 登陆用的源程序~~~不怎么样``但也是我初学的参考的有用的资料
💻 JAVA
字号:
package socket;import javax.microedition.midlet.*;import javax.microedition.io.*;import javax.microedition.lcdui.*;import java.io.*;public class SocketClient 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;		// 套接字连接    InputStream is;				// 输入流    OutputStream os;			// 输出流    Sender sender;				// 用于发送数据的线程	public SocketClient() {        display = Display.getDisplay(this);        f = new Form("Socket Client");        tf = new TextField("发送:", "", 30, TextField.ANY);        si = new StringItem("状态:", " ");        f.append(tf);        f.append(si);        f.addCommand(exitCommand);        f.addCommand(sendCommand);        f.setCommandListener(this);        display.setCurrent(f);	}    public void startApp() {        new Thread(this).start();	// 开始客户端连接的线程    }    public void run() {        try {			// 客户端套接字,连接到主机localhost的5000端口            sc = (SocketConnection) Connector.open("socket://localhost:5000");            si.setText("连接到服务器");		// 设置当前显示的状态            is = sc.openInputStream();		// 打开输入流            os = sc.openOutputStream();		// 打开输出流            sender = new Sender(os);		// 建立线程,用于发送数据            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 (ConnectionNotFoundException e) {			System.out.println("错误:请先运行服务器端");            destroyApp(true);            notifyDestroyed();        } catch (Exception e) {			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();        } 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();        } catch (IOException ioe) {}    }}

⌨️ 快捷键说明

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