ServerSocket向客户端发送消息

时间:2012-02-13 19:07:04

标签: android sockets

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);
    }

}

我从套接字读取消息的块被注释掉了。如果我不评论它,客户端套接字无法建立与服务器的连接。 可能是什么问题?

1 个答案:

答案 0 :(得分:0)

是否有任何错误打印到控制台?

我也是新手,但也许以下事情可行:

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