PDA

View Full Version : Socket Programming on HTC Magic


fyp
15th September 2009, 05:21 AM
Hi, I have made an application on the phone which collects the data from the built-in sensors, and now I'm trying to use socket programming to send the data to my laptop. Basically, I put the following socketing code in my application code and wrote another server program on my laptop to set up the connection between the cellphone and the laptop. But it doesnt seem to work....my phone shows a debug message "No I/O"...meaning, I guess, the phone is actually not sucessfully connected to the laptop. Could anybody pls teach me the right way to do this? communication either through wifi (my laptop and phone both already logged onto the campus network), or usb(the phone is directly connected to the laptop by a usb cable). Thank you!

Client code on the phone:
public void listenSocket(){
//Create socket connection
try{
socket = new Socket("localhost", 4444);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);



} catch (UnknownHostException e) {
socketMsg.setText("Unknown host: localhost");
} catch (IOException e) {
socketMsg.setText("No I/O");
}
}

Server code on the laptop:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class SocketServer1 {
public static void main(String[] args){
ServerSocket server = null;
Socket client = null;
BufferedReader in = null;
PrintWriter out = null;


try{
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}

System.out.println("Server is ready");

try{
client = server.accept();
System.out.println("Server is not accepting data");
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}


try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}




//Clean up
try{
in.close();
out.close();
server.close();
} catch (IOException e) {
System.out.println("Could not close.");
System.exit(-1);
}

}
}
PS. I guess the problem may be the server_name and port_number set on my phone are not correct....