Two methods of J2ME network programming with case analysis

Source: Internet
Author: User
Tags add character set continue connect return socket string client
Programming | Network This paper describes the development of the main network connection method in J2me, and introduces two methods of using HTTP and socket in detail respectively.

httpconnection

Let's first look at a simple example:

Java packages that are used primarily:

javax.microedition.io.*;

public string Requestget (string urlstring,string URL) throws ioexception{
=============================================================
URLString is an HTTP address, and the URL is the following parameter
The example here is the user name and password sent to the server to authenticate the user
such as String urlstring = "http://192.168.0.1:8080/login.jsp";
String URL = "? Name= "+this.txtname+" &pass= "+this.txtpass
=============================================================
    
Httpconnection HPC = null;
DataInputStream dis = null;

Boolean newline = false;

String content = "";
try{
===========================================================
Establish a connection
===========================================================
HPC = (httpconnection) connector.open (Urlstring+url);
Hpc.setrequestmethod (Httpconnection.get);
dis = new DataInputStream (Hpc.openinputstream ());
int character;
===========================================================
Read the returned HTTP content
===========================================================
while ((character = Dis.read ())!=-1) {
if ((char) character = = ' \ ') {
NewLine = true;
Continue
}
else{
if ((char) character = = ' n ' && newline) {
Content + = "\ n";
newline = false;
}
else if (newline) {
Content + = "\" + (char) character;
newline = false;
}
else{
Content + = (char) character;
newline = false;
}
}
}
}
catch (IOException e) {
System.out.print ("ERROR:" +e);
}
finally{
if (HPC!= null) {
Hpc.close ();
HPC = null;
}
if (dis!= null) {
Dis.close ();
}
}
===============================================================
Because the content may have Chinese, the content should be converted to character set after receiving the information
===============================================================
Content = (unicodeTogb2312 (content)). Trim ();
return content;
}

public static string unicodeTogb2312 (string s) {
if (s==null) {return "";}
if (S.equals ("")) {return s;}
try{
return new String (S.getbytes ("Iso8859_1"), "gb2312");
}
catch (Exception uee) {
return s;
}
}


The above is a simple HTTP connection and get response information from the server example, should be very simple. The client is the above, server-side as long as the configuration of IIS, add a Web page to the client's request to respond to the line, in fact, with the general requirements of the Web page is not much different, very simple!!

The above socket client connection program should be completed, the following is to build a server-side connection to the client to respond. To establish a server-side program, you only need the following code:

SocketConnection

The following or from the example to start talking about J2ME socket programming.

The program first opens the socket connection with the IP address as 192.168.0.1:6666 and throws an exception if the connection fails, and the program ends. If the socket connection succeeds, continue.
  

public Boolean socketconn (String s) throws ioexception{

=============================================================
S is the socket connection string
The example here is the user name and password sent to the server to authenticate the user
such as String s = "socket://192.168.0.1:6666"
=============================================================
    
Private Streamconnection conserver;
Private String strserveraddr;
Private Boolean bconnected;
    
Conserver = null;
STRSERVERADDR = s; Connection Address
bconnected = false; Connection Status
    
Try
{
Conserver = (streamconnection) connector.open (STRSERVERADDR);
}
catch (Exception Exception)
{
SYSTEM.OUT.PRINTLN ("Connect server Error");
bconnected = false;
return false;
}
Bconnected = true;
System.out.println ("Connect ok!");
return true;
}


The above socket client connection program should be completed, the following is to build a server-side connection to the client to respond. To establish a server-side program, you only need the following code:

..........
try{
Establish a socket server with a port of 6666
Serversocketconnection Socketser;
Socketser = (serversocketconnection) connector.open ("socket://:6666");
  
Waiting for client connections
SocketConnection SC;
If there is a connection, add a new thread to handle the connection
sc = (socketconnection) socketser.acceptandopen ();
..........
while (true) {
Processing of SC InputStream and OutputStream

}
}
..........


Here need to explain my opinion, mobile phone through the socket connected to the server, because I use the China Mobile number, so running is the GPRS channel, I established the server connection to obtain the client IP is only a virtual IP, And this IP estimate is based on the user's current mobile station encoding through some changes in the production, so when the user is constantly moving, the IP may change (here I am not very clear), interested can go to see "Mobile Virtual IP Technology" related to the report. Originally my idea is that users connect to the server as long as the IP unchanged can be implemented server to the client broadcast data, but this IP is not a long connection, the server in the broadcast data may have a large majority of the client's IP will change, so the last or the client to send the form of unsolicited information. Feel a bit far away, or back to the point of it.

After the client has successfully established the socket connection, it can send the information to the server, the following is the sending information module

Protected Boolean SendData (Byte abyte0[])//replace yourself []
{
System.out.println ("Send:" + bconnected);
Determining connection Conditions
if (!bconnected)
return false;
OutputStream outputstream = null;
Try
{
OutputStream = Conserver.openoutputstream ();
Write information to OutputStream
Outputstream.write (ABYTE0);
My understanding is to force the sending of all the information that has been written.
Outputstream.flush ();
Outputstream.close ();
}
catch (Exception Exception)
{
System.out.println ("Send Data error");
bconnected = false;
Try
{
if (OutputStream!= null)
Outputstream.close ();
Call a disconnected function
Disconnect ();
}
catch (Exception exception1) {}
return false;
}
return true;
}

  
The following is read the server response information, the other is not one of the said, the OutputStream to InputStream, and then use the InputStream Read method can be.

..............
InputStream = Conserver.openinputstream ();
..............


The above is the main use of J2ME Development network connection methods, including HTTP and socket, and other datagram and so on, that because I have not used, so it is not easy to talk about, basically the above two kinds of network development is enough, how, is not very simple. The above views and views belong to their humble opinion, if there is a mistake, please point out the master.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.