📄 sockettest.java
字号:
//SocketTest.java
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class SocketTest extends MIDlet implements CommandListener
{
private Command exitCommand, testCmd;//命令对象
private Form form;
private TextField tfSvr,tfRecv,tfSend; //通过TextField来显示信息
private Ticker tker; //访问网络时显示滚动的标题
public SocketTest()
{
form = new Form("TCP Test");
tfSvr =new TextField("server","socket://127.0.0.1:3000",120,TextField.URL);
tfSend =new TextField("send","abcdefg",120,TextField.ANY);
tfRecv =new TextField("receive","",120,TextField.ANY);
tker = new Ticker("Testing");
form.append(tfSvr);
form.append(tfSend);
form.append(tfRecv);
exitCommand =new Command("Exit",Command.EXIT,1);
testCmd =new Command("Send&Recv",Command.SCREEN,1);
form.addCommand(exitCommand);
form.addCommand(testCmd);
form.setCommandListener(this);
}
protected void startApp( ) throws MIDletStateChangeException
{
Display.getDisplay(this).setCurrent(form);
}
protected void pauseApp( )
{
}
protected void destroyApp( boolean p1 )
{
}
public void commandAction(Command c,Displayable d)
{
if (c ==exitCommand)
{
destroyApp(false);
notifyDestroyed();
}
else if(c ==testCmd)
{
form.setTicker(tker);
new Client(form,tfRecv, tfSvr.getString(),tfSend.getString());
}
}
private class Client extends Thread
{
private String connStr;
private String strSend , strRecv;
private Form form; //在读入数据完成后停止窗口的滚动标题
private TextField tfRecv;
public Client(Form f, TextField tf, String svr, String send)
{
form = f;
tfRecv = tf;
connStr = svr;
strSend = send;
this.start();
}
public void run()
{
try
{
strRecv = exchangeString(connStr, strSend);
}
catch(Exception e)
{System.out.println("error = "+e.getMessage());}
form.setTicker(null); //停止滚动标题
tfRecv.setString(strRecv);//设置接收到的字符串
}
public String exchangeString(String svr, String send) throws IOException
{//通过 SocketConnection 对象与TCP 服务器通信
SocketConnection sc = null;
DataOutputStream dos = null; //输出流
DataInputStream dis = null; //输入流
String recv=null;
try
{
//创建 SocketConnection 对象,并连接到服务器
sc = (SocketConnection)Connector.open(svr);
dos = sc.openDataOutputStream();//打开输出流
dis = sc.openDataInputStream();//打开输入流
dos.writeUTF(send);//向服务器发送数据
recv = dis.readUTF();//从服务器接收输入
}
catch (IOException e)
{
System.out.println("error = "+e.getMessage());
}
finally
{//关闭所有对象
if (dis != null)
dis.close();
if (dos != null)
dos.close();
if (sc != null)
sc.close();
}
return recv;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -