关于手机开发socket笔记。
2009年11月06日
midlet类:ScoketProgram.java
package src;
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDletStateChangeException;
public class ScoketProgram extends MIDlet implements CommandListener{
private static final String SERVER="Server";
private static final String CLIENT="Client";
private static final String[] name={SERVER,CLIENT};
private static Display display;
private Form f;
private ChoiceGroup cg;
private boolean isPaused;
private Server server;
private Client client;
private Command exitCommand=new Command("Exit",Command.EXIT,1);
private Command startCommand=new Command("Start",Command.ITEM,1);
public ScoketProgram() {
display=Display.getDisplay(this);
f=new Form("Socket Demo");
cg=new ChoiceGroup("Please select peer",Choice.EXCLUSIVE,name,null);
f.append(cg);
f.addCommand(exitCommand);
f.addCommand(startCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public boolean isPaused()
{
return isPaused;
}
protected void destroyApp(boolean arg0) {
if(server!=null)
{
server.stop();
}
if(client!=null)
{
client.stop();
}
// TODO 自动生成方法存根
}
protected void pauseApp() {
isPaused=true;
// TODO 自动生成方法存根
}
protected void startApp() {
isPaused=false;
// TODO 自动生成方法存根
}
public void commandAction (Command c,Displayable s)
{
if(c==exitCommand)
{
try
{
destroyApp(true);
}
catch(Exception e)
{}
notifyDestroyed();
}else if(c==startCommand){
String name =cg.getString(cg.getSelectedIndex());
System.out.print(name);
//System.out.print("77777777777777777777");
if(name.equals(SERVER))
{
server =new Server(this);
server.start();
}else{
client=new Client(this);
client.start();
}
}
}
}
服务器端:server.java
package src;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class Server implements Runnable,CommandListener{
private ScoketProgram parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand=new Command("Send",Command.ITEM,1);
private Command exitCommand=new Command("Exit",Command.EXIT,1);
//声明服务器的输入流和输出流
InputStream is;
OutputStream os;
//服务器端得scoket
SocketConnection sc;
ServerSocketConnection scn;
Sender sender;
public Server(ScoketProgram m)
{
parent=m;
display=Display.getDisplay(parent);
f=new Form("Socket Server");
si=new StringItem("Status:"," ");
tf=new TextField("Send:","",30,TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public void start()
{
//Thread t=new Thread();
// new Thread(this).start();
Thread t1 = new Thread(this);
t1.start();
}
public void run()
{
try{
si.setText("Waiting for connection");
scn=(ServerSocketConnection) Connector.open("socket://:1023");
sc=(SocketConnection) scn.acceptAndOpen(); //此时服务器端处于等待客户端连接状态
si.setText("Connection accepted");//客户端连接后执行!
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("Message receiver-"+sb.toString());
}
stop();
si.setText("Connection is closed");//客户端退出将触发
f.removeCommand(sendCommand);
}catch(IOException ioe) {
if(ioe.getMessage().equals("SeverSocket 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 commandAction(Command c,Displayable s)
{
if(c==sendCommand &&!parent.isPaused())
{
sender.send(tf.getString());
}
if((c==Alert.DISMISS_COMMAND) || (c==exitCommand)){
parent.notifyDestroyed();
try
{
parent.destroyApp(true);
}
catch (Exception e)
{
}
}
}
/*
* 关闭打开流
*
* */
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 ioe)
{
}
}
}
客户端:
package src;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class Client implements Runnable,CommandListener{
private ScoketProgram parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand=new Command("Send",Command.ITEM,1);
private Command exitCommand=new Command("Exit",Command.EXIT,1);
//声明服务器的输入流和输出流
InputStream is;
OutputStream os;
//服务器端得scoket
SocketConnection sc;
ServerSocketConnection scn;
Sender sender;
public Client(ScoketProgram m)
{
parent=m;
display=Display.getDisplay(parent);
f=new Form("Socket Clent");
si=new StringItem("Status:"," ");
tf=new TextField("Send:","",30,TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public void start()
{
Thread t2 = new Thread(this);
t2.start();
}
public void run()
{
try{
//sc=(SocketConnection) Connector.open("socket://127.0.0.1:1023");
sc = (SocketConnection) Connector.open("socket://127.0.0.1:1023");
//sc=(SocketConnection) scn.acceptAndOpen();
si.setText("Connection to server");
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("Message receiver-"+sb.toString());
}
stop();
si.setText("Connection is closed");//服务器退出将触发
f.removeCommand(sendCommand);
}catch(ConnectionNotFoundException cnfe) {
Alert a =new Alert("Client","Port 5000 is already taken",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 s)
{
if(c==sendCommand &&!parent.isPaused())
{
System.out.println(tf.getString());
System.out.println("9999999999999999999");
sender.send(tf.getString());
}
if((c==Alert.DISMISS_COMMAND) || (c==exitCommand)){
parent.notifyDestroyed();
try{
parent.destroyApp(true);}
catch(Exception e){}
}
}
/*
* 关闭打开流
*
* */
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 ioe)
{
}
}
}
共用sender:
package src;
import java.io.*;
public class Sender extends Thread {
private OutputStream os;
private String message;
public Sender (OutputStream os)
{
this.os=os;
start();
}
public synchronized void send(String msg)
{
message=msg;
notify();
}
public synchronized void run()
{
while(true)
{
if (message==null)
{
try
{
/*
*
* 在Runnable接口定义的线程里,有两种等待方法,
* 一种是wait,一种是sleep,如果使用wait()方法,则要注意在线程run方法里,
* 用synchonized标志符将该线程设置为同步锁定状态,否则会出现java.lang.
* IllegalMonitorStateException异常,大致意思是线程当前请求的监视器对象不能响应,
* 因为被别的线程占用了。
*/
wait();
}
catch(InterruptedException e)
{
}
}
if(message==null)
{
break;
}
try{
os.write(message.getBytes());
os.write("\r\n".getBytes());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
public synchronized void stop()
{
message=null;
notify();
// toString() ;
}
}
2009年11月06日
midlet类:ScoketProgram.java
package src;
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDletStateChangeException;
public class ScoketProgram extends MIDlet implements CommandListener{
private static final String SERVER="Server";
private static final String CLIENT="Client";
private static final String[] name={SERVER,CLIENT};
private static Display display;
private Form f;
private ChoiceGroup cg;
private boolean isPaused;
private Server server;
private Client client;
private Command exitCommand=new Command("Exit",Command.EXIT,1);
private Command startCommand=new Command("Start",Command.ITEM,1);
public ScoketProgram() {
display=Display.getDisplay(this);
f=new Form("Socket Demo");
cg=new ChoiceGroup("Please select peer",Choice.EXCLUSIVE,name,null);
f.append(cg);
f.addCommand(exitCommand);
f.addCommand(startCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public boolean isPaused()
{
return isPaused;
}
protected void destroyApp(boolean arg0) {
if(server!=null)
{
server.stop();
}
if(client!=null)
{
client.stop();
}
// TODO 自动生成方法存根
}
protected void pauseApp() {
isPaused=true;
// TODO 自动生成方法存根
}
protected void startApp() {
isPaused=false;
// TODO 自动生成方法存根
}
public void commandAction (Command c,Displayable s)
{
if(c==exitCommand)
{
try
{
destroyApp(true);
}
catch(Exception e)
{}
notifyDestroyed();
}else if(c==startCommand){
String name =cg.getString(cg.getSelectedIndex());
System.out.print(name);
//System.out.print("77777777777777777777");
if(name.equals(SERVER))
{
server =new Server(this);
server.start();
}else{
client=new Client(this);
client.start();
}
}
}
}
服务器端:server.java
package src;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class Server implements Runnable,CommandListener{
private ScoketProgram parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand=new Command("Send",Command.ITEM,1);
private Command exitCommand=new Command("Exit",Command.EXIT,1);
//声明服务器的输入流和输出流
InputStream is;
OutputStream os;
//服务器端得scoket
SocketConnection sc;
ServerSocketConnection scn;
Sender sender;
public Server(ScoketProgram m)
{
parent=m;
display=Display.getDisplay(parent);
f=new Form("Socket Server");
si=new StringItem("Status:"," ");
tf=new TextField("Send:","",30,TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public void start()
{
//Thread t=new Thread();
// new Thread(this).start();
Thread t1 = new Thread(this);
t1.start();
}
public void run()
{
try{
si.setText("Waiting for connection");
scn=(ServerSocketConnection) Connector.open("socket://:1023");
sc=(SocketConnection) scn.acceptAndOpen(); //此时服务器端处于等待客户端连接状态
si.setText("Connection accepted");//客户端连接后执行!
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("Message receiver-"+sb.toString());
}
stop();
si.setText("Connection is closed");//客户端退出将触发
f.removeCommand(sendCommand);
}catch(IOException ioe) {
if(ioe.getMessage().equals("SeverSocket 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 commandAction(Command c,Displayable s)
{
if(c==sendCommand &&!parent.isPaused())
{
sender.send(tf.getString());
}
if((c==Alert.DISMISS_COMMAND) || (c==exitCommand)){
parent.notifyDestroyed();
try
{
parent.destroyApp(true);
}
catch (Exception e)
{
}
}
}
/*
* 关闭打开流
*
* */
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 ioe)
{
}
}
}
客户端:
package src;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class Client implements Runnable,CommandListener{
private ScoketProgram parent;
private Display display;
private Form f;
private StringItem si;
private TextField tf;
private boolean stop;
private Command sendCommand=new Command("Send",Command.ITEM,1);
private Command exitCommand=new Command("Exit",Command.EXIT,1);
//声明服务器的输入流和输出流
InputStream is;
OutputStream os;
//服务器端得scoket
SocketConnection sc;
ServerSocketConnection scn;
Sender sender;
public Client(ScoketProgram m)
{
parent=m;
display=Display.getDisplay(parent);
f=new Form("Socket Clent");
si=new StringItem("Status:"," ");
tf=new TextField("Send:","",30,TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public void start()
{
Thread t2 = new Thread(this);
t2.start();
}
public void run()
{
try{
//sc=(SocketConnection) Connector.open("socket://127.0.0.1:1023");
sc = (SocketConnection) Connector.open("socket://127.0.0.1:1023");
//sc=(SocketConnection) scn.acceptAndOpen();
si.setText("Connection to server");
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("Message receiver-"+sb.toString());
}
stop();
si.setText("Connection is closed");//服务器退出将触发
f.removeCommand(sendCommand);
}catch(ConnectionNotFoundException cnfe) {
Alert a =new Alert("Client","Port 5000 is already taken",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 s)
{
if(c==sendCommand &&!parent.isPaused())
{
System.out.println(tf.getString());
System.out.println("9999999999999999999");
sender.send(tf.getString());
}
if((c==Alert.DISMISS_COMMAND) || (c==exitCommand)){
parent.notifyDestroyed();
try{
parent.destroyApp(true);}
catch(Exception e){}
}
}
/*
* 关闭打开流
*
* */
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 ioe)
{
}
}
}
共用sender:
package src;
import java.io.*;
public class Sender extends Thread {
private OutputStream os;
private String message;
public Sender (OutputStream os)
{
this.os=os;
start();
}
public synchronized void send(String msg)
{
message=msg;
notify();
}
public synchronized void run()
{
while(true)
{
if (message==null)
{
try
{
/*
*
* 在Runnable接口定义的线程里,有两种等待方法,
* 一种是wait,一种是sleep,如果使用wait()方法,则要注意在线程run方法里,
* 用synchonized标志符将该线程设置为同步锁定状态,否则会出现java.lang.
* IllegalMonitorStateException异常,大致意思是线程当前请求的监视器对象不能响应,
* 因为被别的线程占用了。
*/
wait();
}
catch(InterruptedException e)
{
}
}
if(message==null)
{
break;
}
try{
os.write(message.getBytes());
os.write("\r\n".getBytes());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
public synchronized void stop()
{
message=null;
notify();
// toString() ;
}
}