2012-02-13 6 views
0
public class Server extends AsyncTask<Void, Intent, Void> { 

    private final Context context; 

    public Server(Context context) { 
     this.context = context; 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      ServerSocket server = new ServerSocket(12345); 
      while (true) { 
       Socket client = server.accept(); 

       // send message 
       OutputStream outputStream = client.getOutputStream(); 
       String message = "Hello Android! - Send from Server."; 
       outputStream.write(message.getBytes()); 

       // THIS DONT WORK FOR SOME REASONS read message 
       String response = ""; 
//    InputStream inputStream = client.getInputStream(); 
//    response = Utils.inputStreamToString(inputStream); 


       // notify ServerService 
       Intent intent = new Intent(Messenger.ACTION); 
       intent.putExtra("action", Messenger.SERVER_NEW_CLIENT_CONNECTED); 
       intent.putExtra("message", "Message: " + response); 
       publishProgress(intent); 

       client.close(); 
      } 
      server.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onProgressUpdate(Intent... value) { 
     if (value.length == 0) 
      return; 
     Intent data = value[0]; 
     context.sendBroadcast(data); 
    } 

} 

私がソケットからメッセージを読み込んだブロックはコメントアウトされています。コメントアウトしないと、クライアントソケットはサーバーへの接続を確立できません。 何が問題なのですか?ServerSocketはクライアントにメッセージを送信します

答えて

0

コンソールにエラーが印刷されていますか?

私も初心者だけど、多分、次の事は仕事ができる:

DataIntputStream input = new DataInputStream(client.getInputStream()) ; 
byte[] b = new byte[1024] 
input.read(b) ; 
String inputString = new String(b) ; 
+0

コンソールとlogcatに誤りがありません。あなたの方法はあまり意味がありませんが、私はそれを試してみます。 –

+0

これは私が私のserver-clientに使用している方法であり、動作します。 – tb96

関連する問題