I’ve writen a function to send and receive message from server like this:
//Send mess to server through socket
public boolean send_Message_service(String mess) throws IOException{
Log.i("debug", "Connection status: "+String.valueOf(this.clientSocket.isBound()));
boolean rs=false;
//Send mess toi server
BufferedReader in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(this.clientSocket.getOutputStream())), true);
out.println(mess);
//Receive mess from server
String mess_From_Server=in.readLine();
if(mess_From_Server.equalsIgnoreCase("success")){
rs=true;
}
else{
rs=false;
}
return rs;
}
That function can send message to server but cannot receive message from server, when I run it with my phone, it’s take a long time and Force Close!
Here is the logcat:
10-11 12:17:35.201: INFO/global(279): Default buffer size used in BufferedWriter constructor. It would be better to be explicit if an 8k-char buffer is required.
10-11 12:21:26.321: DEBUG/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
And here is code of server (run on Java not Android):
int receiveMsgSize;//Size of received message
byte[] receiveBuf= new byte[100]; //Receive Buffer
try {
ObjectOutputStream oos = new ObjectOutputStream(this.clientSocket.getOutputStream());
InputStream in;
in = this.clientSocket.getInputStream();
while((receiveMsgSize=in.read(receiveBuf))!=-1){
String mess=new String(receiveBuf,0,receiveMsgSize);
System.out.println(mess.length());
System.out.println(mess);
}
oos.writeObject("success");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is never going to work.
If you have an ObjectOutputStream at one end you must have an ObjectInputStream at the other end.
If you have writeObject() at one end you must have readObject() at the other end.
If you have writeXXX() at one end you must have readXXX() at the other end, for all XXX that I can think of.
Or conversely if you have BufferedReader.readLine() at one end you must have BufferedWriter.write() followed by BufferedWriter.newLine() at the other end.
Don’t use PrintStream or PrintWriter over a network, as they swallow exceptions you need to know about.