2012-02-13 176 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的没有错误。你的方法对我来说没有多大意义,但我会尝试。 – 2012-02-13 21:17:52

+0

这是我用于我的服务器客户端的一种方法,它可以工作。 – tb96 2012-02-13 21:46:18