服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

j2me中使用socket开发联网程序


  在j2me中基于udp协议编程一文中介绍了如何使用datagram和datagramconnection来开发应用程序,本文将主要讲述在midp2.0中使用serversocketconnection和socketconnection来开发联网应用程序。tcp协议是可以保证传输的质量的,这也是他和udp的一大区别。由于以上谈到的四个类都属于gcf,他们在程序编写方面也非常相似,通常我们在server端的某个端口监听,当客户端连接服务器的时候,则可以得到一个socketconnection的实例。通过两端的socketconnection则可以实现c/s结构的通信了。

  首先看一下,serversocketconnection类,它的一个非常重要的方法就是acceptandopen()方法,这个方法返回一个socketconnection实例,从而使得客户端和服务器端可以通过socket通信了。典型的代码如下:

// create the server listening socket for port 1234
serversocketconnection scn = (serversocketconnection)
connector.open("socket://:1234");

// wait for a connection.
socketconnection sc = (socketconnection) scn.acceptandopen();

// set application specific hints on the socket.
sc.setsocketoption(delay, 0);
sc.setsocketoption(linger, 0);
sc.setsocketoption(keepalive, 0);
sc.setsocketoption(rcvbuf, 128);
sc.setsocketoption(sndbuf, 128);

// get the input stream of the connection.
datainputstream is = sc.opendatainputstream();

// get the output stream of the connection.
dataoutputstream os = sc.opendataoutputstream();

// read the input data.
string result = is.readutf();

// echo the data back to the sender.
os.writeutf(result);

// close everything.
is.close();
os.close();
sc.close();
scn.close();
..


socketconnection的使用也是非常简单,通过connector的open方法我们可以得到一个socketconnection的实例。
socketconnection sc = (socketconnection)
connector.open("socket://host.com:79");
sc.setsocketoption(socketconnection.linger, 5);

inputstream is = sc.openinputstream();
outputstream os = sc.openoutputstream();

os.write("/r/n".getbytes());
int ch = 0;
while(ch != -1) {
 ch = is.read();
}

is.close();
os.close();
sc.close();

  其实我们在用socket编写程序的时候无非遵循这样的一种规则:服务器端建立监听端口等待连接,客户端通过open()方法与服务器端建立连接,两端通过建立的socket传输数据,关闭连接。
  下图是我在运行wtk中networkdemo的时候的截图!代码也一并发表出来。

j2me中使用socket开发联网程序

package socket;

import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;

public class socketmidlet extends midlet implements commandlistener {
 private static final string server = "server";
 private static final string client = "client";
 private static final string[] names = { 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 socketmidlet() {
  display = display.getdisplay(this);
  f = new form("socket demo");
  cg = new choicegroup("please select peer", choice.exclusive, names,null);
  f.append(cg);

  f.addcommand(exitcommand);
  f.addcommand(startcommand);
  f.setcommandlistener(this);

  display.setcurrent(f);
 }

 public boolean ispaused() {
  return ispaused;
 }

 public void startapp() {
  ispaused = false;
 }

 public void pauseapp() {
  ispaused = true;
 }

 public void destroyapp(boolean unconditional) {
  if (server != null) {
   server.stop();
  }
  if (client != null) {
   client.stop();
  }
 }

 public void commandaction(command c, displayable s) {
  if (c == exitcommand) {
   destroyapp(true);
   notifydestroyed();
  } else if (c == startcommand) {
   string name = cg.getstring(cg.getselectedindex());
   if (name.equals(server)) {
    server = new server(this);
    server.start();
   } else {
    client = new client(this);
    client.start();
   }
  }
 }

}

package socket;

import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;

public class server implements runnable, commandlistener {
 private socketmidlet 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;
 socketconnection sc;
 serversocketconnection scn;
 sender sender;
 
 public server(socketmidlet 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(exitcommand);
  f.setcommandlistener(this);
  display.setcurrent(f);
 }

 public void start() {
  thread t = new thread(this);
  t.start();
 }

 public void run() {
  try {
   si.settext("waiting for connection");
   scn = (serversocketconnection) connector.open("socket://:5009");

   // wait for a connection.
   sc = (socketconnection) scn.acceptandopen();
   si.settext("connection accepted");
   is = sc.openinputstream();
   os = sc.openoutputstream();
   sender = new sender(os);
 
   // allow sending of messages only after sender is created
   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 received - " + sb.tostring());
   }
   stop();
   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 commandaction(command c, displayable s) {
  if (c == sendcommand && !parent.ispaused()) {
   sender.send(tf.getstring());
  }

  if ((c == alert.dismiss_command) || (c == exitcommand)) {
   parent.notifydestroyed();
   parent.destroyapp(true);
  }
 }

/**
* close all open streams
*/

 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 socket;

import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.io.*;

public class client implements runnable, commandlistener {
 private socketmidlet 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;
 socketconnection sc;
 sender sender;

 public client(socketmidlet m) {
  parent = m;
  display = display.getdisplay(parent);
  f = new form("socket client");
  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);
 }

 /**
 * start the client thread
 */
 public void start() {
  thread t = new thread(this);
  t.start();
 }

 public void run() {
  try {
   sc = (socketconnection) connector.open("socket://localhost:5009");
   si.settext("connected to server");
   is = sc.openinputstream();
   os = sc.openoutputstream();

   // start the thread for sending messages - see sender's main
   // comment for explanation
   sender = new sender(os);
 
   // loop forever, receiving data
   while (true) {
    stringbuffer sb = new stringbuffer();
    int c = 0;
    while (((c = is.read()) != '/n') && (c != -1)) {
     sb.append((char) c);
    }

    if (c == -1) {
     break;
    }
    // display message to user
    si.settext("message received - " + sb.tostring());
   }
   stop();
   si.settext("connection closed");
   f.removecommand(sendcommand);
  } catch (connectionnotfoundexception cnfe) {
   alert a = new alert("client", "please run server midlet 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 s) {
 if (c == sendcommand && !parent.ispaused()) {
  sender.send(tf.getstring());
 }

 if ((c == alert.dismiss_command) || (c == exitcommand)) {
  parent.notifydestroyed();
  parent.destroyapp(true);
 }
}

/**
* close all open streams
*/

public void stop() {
 try {
  stop = true;
 
  if (sender != null) {
   sender.stop();
  }

  if (is != null) {
   is.close();
  }

  if (os != null) {
   os.close();
  }

  if (sc != null) {
   sc.close();
  }
 } catch (ioexception ioe) {
}
}
}

package socket;

import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
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 no client to deal, wait until one connects
   if (message == null) {
    try {
     wait();
    } catch (interruptedexception e) {
    }
   }

   if (message == null) {
    break;
   }

   try {
    os.write(message.getbytes());
    os.write("/r/n".getbytes());
   } catch (ioexception ioe) {
   ioe.printstacktrace();
  }

  // completed client handling, return handler to pool and
  // mark for wait
  message = null;
 }
}

public synchronized void stop() {
 message = null;
 notify();
}
}

扫描关注微信公众号