簡體   English   中英

如何使用 Socket.IO-client Java 從 Android 向服務器發送 String 消息?

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

我使用socket.io-client-java

我有 android 客戶端和 Java 服務器

服務器代碼:

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

和客戶:

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

如果我嘗試連接到服務器,我會得到這個:

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

但是當我嘗試發送 String 消息時

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

沒發生什么事。 是我發送錯誤還是服務器錯誤?

要正確初始化socket.io客戶端,您需要執行以下操作:

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

每個偵聽器在事件發生時運行,例如:

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

當您從服務器收到新消息時,將觸發call()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM