728x90


저번에는 NodeJS와 Java와 통신을 했는데 이번에는 안드로이드와 통신을 하도록 하자.

자바보다는 안드로이드와의 정책때문에 몇가지 작업을 더해줘야한다.


implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
implementation group: 'io.socket', name: 'socket.io-client', version: '1.0.0'

이렇게 두가지를 추가해준다.



자 이렇게 바꾸고나면 위에 Sync Now가 생긴다. 이게 없어질때까지 눌러준다.



아래에 빌드에 초록불이 모두 들어 왔는지 확인한다.



또한 람다식을 쓸건데 람다식을 추가시켜줘야한다.



이렇게 눌러서 추가해준다.

화면에는 Module Settings에 마우스가 올라가 있지만 아랫걸 눌러줘야한다.



그 다음 Manifeset에서 INTERNET을 추가해줘야한다.

왜냐하면 Socket통신을 하려면 열어줘야하기 때문이다.

그리고 예제에 쓸 레이아웃을 보도록 하자.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.97"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.03"
android:weightSum="1"
android:orientation="horizontal">

<EditText
android:id="@+id/etMsg"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.7"
android:gravity="center"
android:hint="입력하세요"/>

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:text="제출" />
</LinearLayout>
</LinearLayout>

이 레이아웃은 아주 간단하다.

그리 코드를 보도록하자.


package hack.the.wap.socketio;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;

public class MainActivity extends AppCompatActivity {
private TextView tvMain;
private EditText etMsg;
private Button btnSubmit;
private Socket socket;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMain = findViewById(R.id.tvMain);
etMsg = findViewById(R.id.etMsg);
btnSubmit = findViewById(R.id.btnSubmit);

btnSubmit.setOnClickListener((view)->{
JsonObject preJsonObject = new JsonObject();
preJsonObject.addProperty("comment", etMsg.getText()+"");
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(preJsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
socket.emit("reqMsg", jsonObject);
etMsg.setText("");
});

try {
socket = IO.socket("http://172.16.101.127:3100");
socket.on(Socket.EVENT_CONNECT, (Object... objects) -> {
JsonObject preJsonObject = new JsonObject();
preJsonObject.addProperty("roomName", "myroom");
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(preJsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
socket.emit("joinRoom",jsonObject);
}).on("recMsg", (Object... objects) -> {
JsonParser jsonParsers = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParsers.parse(objects[0] + "");
runOnUiThread(()->{
tvMain.setText(tvMain.getText().toString()+jsonObject.get("comment").getAsString());
});
});
socket.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
}


코드의 해석은 3장을 확인하도록 하자.

이제 실행해보도록 하자.



제대로 동작하는지 확인하도록 하자

+ Recent posts