Sunday, December 9, 2007

How to use mobile as a network server

This Java ME tip explains use of handset (Mobile) as network Server. This tip may be helpful for game developers who are coming up with applications which work on more than one mobile device. This may help them to make one handset controlling the activities of the other.

String getResponse(String request) {
String response="";

try{
// Open a socket connection
//It is trying to connect to a server at port no 8080
SocketConnection soc=Connector.open("socket://my.com:8080");

//Open input and output streams
InputStream is = soc.openInputStream();
OutputStream os = soc.openOutputStream();

//Sending request to server
os.write(request.getBytes());

//Now read response from server one byte at a time
int ch = 0;
while(ch != -1) {
ch = is.read();
response+=(char)ch;

}

//Close connection
is.close();
os.close();
soc.close();
}catch(Exception e){}

return response;
}


void startServer() {

try {

// Open a server socket connection
// It is trying start a server at port no 8080

ServerSocketConnection serv =
(ServerSocketConnection)Connector.open("socket://:8080");

while(true) {

// Now server is passive open:waiting
SocketConnection soc = (SocketConnection) scn.acceptAndOpen();

//Open input and output streams
InputStream is = soc.openInputStream();
OutputStream os = soc.openOutputStream();

//Reading request from client
int ch = 0;
while(ch != -1) {

ch = is.read();
request+=(char)ch;
}
//Send request to server

os.write("Hello from JJKK".getBytes());


//Close connection
is.close();
os.close();
soc.close();
}

}catch(Exception e){}

}

No comments: