서버와 클라이언트의 네트워킹 코드를 액티비티에 넣었을 경우에
시스템의 리소스 상황에 따라 액티비티가 언제라도 종료될수 있다.
따라서 서버가 죽어버리는 상황이 발생하기에
서버를 스레드보다 서비스로 실행하는게 더 안전하다.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//ServerThread thread = new ServerThread();
//thread.start();
Intent intent = new Intent(getApplicationContext(),ChatService.class);
startService(intent);
}
});
}
}
public class ChatService extends Service {
public ChatService() {
}
@Override
public void onCreate() {
super.onCreate();
ServerThread thread = new ServerThread();
thread.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
class ServerThread extends Thread { //5001번 포트에서 대기하는 서버
public void run() {
int port = 5001;
try {
ServerSocket server = new ServerSocket(port);
Log.d("ServerThread","서버가 실행됨.");
while(true) {
Socket socket = server.accept();
ObjectInputStream instream = new ObjectInputStream(socket.getInputStream());
Object input = instream.readObject();
Log.d("ServerThread","input : " + input);
ObjectOutputStream outstream = new ObjectOutputStream(socket.getOutputStream());
outstream.writeObject(input + " from server.");
outstream.flush();
Log.d("ServerThread","output 보냄.");
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}}}
}
public class MainActivity extends AppCompatActivity {
TextView textView;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClientThread thread = new ClientThread();
thread.start();
}
});
}
class ClientThread extends Thread {
public void run() {
int port = 5001;
String host = "localhost";
try {
Socket socket = new Socket(host,port); //소켓 객체 생성
ObjectOutputStream outStream = new ObjectOutputStream(socket.getOutputStream());
outStream.writeObject("안녕!");
outStream.flush();
Log.d("ClientThread","서버로 보냄.");
ObjectInputStream instream = new ObjectInputStream(socket.getInputStream());
final Object input = (String) instream.readObject(); // 서버로 부터 받은 데이터 , 핸들러 접근 가능하게 final 상수처럼 취급
Log.d("ClientThread", "받은 데이터 : " + input);
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("받은 데이터 : " + input);
}
});
} catch (Exception e) {
e.printStackTrace();
}}}
}
- 서버
- 클라이언트