BufferedWriter.write() does not seem to work
android, bufferedwriter, java, sockets
Solution
Your server is expecting a complete line terminated by a newline. Try:
bw.write("Hello Server!");
bw.newLine();
Problem
I have two Java applications, where an Android client connects to a server on a computer and sends a message using BufferedWriter over websockets. The client: ``` try { toast("Sending..."); Socket sock = new Socket(ip, PORT); OutputStream os = sock.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); bw.flush(); bw.write("Hello Server!"); toast("Connected!"); } catch (UnknownHostException e) { toast(e.getMessage()); } catch (IOException e) { toast(e.getMessage()); } ``` The server: ``` public static void main(String[] args) { ServerSocket server; ConnectionThread ct; Socket s; ExecutorService es = Executors.newSingleThreadExecutor(); try { System.out.println("Starting server..."); server = new ServerSocket(1337); s = server.accept(); ct = new ConnectionThread(s); es.execute(ct); } catch (IOException ex) { ex.printStackTrace(); } } ``` The `ConnectionThread` class: ``` public class ConnectionThread implements Runnable { private Socket sock; private InputStream is; private BufferedReader br; private boolean online; public ConnectionThread(Socket s) { System.out.println("Creating connection thread."); this.sock = s; online = true; } @Override public void run() { String input = ""; try { System.out.println("Starting to read..."); is = sock.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); while (online) { input = br.readLine(); if(input != null){ System.out.print("Received message: "); System.out.println(input); } } br.close(); is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` When I run the server, and then the client, the client will show the "Connected!" toast, and the server's output will be: ``` Starting server... Creating connection thread. Starting to read... ``` So, it seems like the connection is actually being made, but the message does not arrive. Does anybody know why this could be happening?