简体   繁体   中英

How send String message to server from Android with Socket.IO-client Java?

I use socket.io-client-java library

I have android client and Java server

Server code:

public class Server {
public static void main(String[] args) throws IOException {
    System.out.println("Welcome to Server side");
    BufferedReader in = null;
    PrintWriter out = null;

    ServerSocket servers = null;
    Socket fromclient = null;

    // create server socket
    try {
        servers = new ServerSocket(4444);
    } catch (IOException e) {
        System.out.println("Couldn't listen to port 4444");
        System.exit(-1);
    }

    try {
        System.out.print("Waiting for a client...");
        fromclient = servers.accept();
        System.out.println("Client connected");
    } catch (IOException e) {
        System.out.println("Can't accept");
        System.exit(-1);
    }

    in = new BufferedReader(new
            InputStreamReader(fromclient.getInputStream()));
    out = new PrintWriter(fromclient.getOutputStream(), true);
    String input, output;

    System.out.println("Wait for messages");
    while ((input = in.readLine()) != null) {
        if (input.equalsIgnoreCase("exit")) break;
        out.println("S ::: " + input);
        System.out.println(input);
    }
    out.close();
    in.close();
    fromclient.close();
    servers.close();
}
}

And client:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Socket mSocket = null;
private Button button;

    {
    try {
        mSocket = IO.socket(Constants.CHAT_SERVER_URL);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(this);
    mSocket.connect();
}

@Override
public void onClick(View v) {
    if (v.getId() == R.id.button){
        mSocket.emit("new message", "Some message");
    }
}
}

And if I tried connect to server I get this:

Welcome to Server side
Waiting for a client...Client connected
Wait for messages
GET /socket.io/?EIO=3&transport=polling HTTP/1.1
User-Agent: Dalvik/1.4.0 (Linux; U; Android 2.3.7; Android SDK built for x86 Build/GINGERBREAD)
Host: 10.0.2.2:4444
Connection: Keep-Alive
Accept-Encoding: gzip

But when I tried to send String message

mSocket.emit("new message", "Some message");

Nothing happens. I send the wrong or server is wrong?

To properly init socket.io client, you need to do something like this:

  Socket _socket = IO.socket(SERVER_URI);
        _socket.on(Socket.EVENT_CONNECT, _onConnectionListener)
                .on(Socket.EVENT_DISCONNECT, _onDisconnectListener)
                .on(Socket.EVENT_CONNECT_ERROR, _onConnectionErrorListener)
                .on(Socket.EVENT_MESSAGE, _onMessageReceivedListener)
                .on(CHAT_MESSAGE_PUBLISH, _onMessageReceivedListener);

Each of listeners is run when the event takes place, eg:

private Emitter.Listener _onMessageReceivedListener = new Emitter.Listener() {
    @Override
    public void call(Object... args) {

        JSONArray jsonArray = (JSONArray) args[0];
        if (jsonArray != null && jsonArray.length() > 0) {
            Gson gson = new Gson();

            List<MessageModel> historyList = gson.fromJson(jsonArray.toString(), listType);
            loadReceivedMessage(historyList);

            chatLoging(jsonArray.toString());
        }
    }
};

The call() method will be triggered when you a receive new message from the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM