mainActivity.java
package com.example.socket;
import java.io.*;
import java.net.*;
import android.app.Activity;
import android.os.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
public class MainActivity extends Activity {
EditText input;
// 서버에서 전송된 메시지를 저장할 변수
String mes = "";
// 서버에서 메시지가 전송되었을 때 호출될 핸들러
Handler handler = new Handler() {
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, mes, Toast.LENGTH_LONG).show();
}
};
//실제 서버에서 접속해서 데이터를 전송하고 전송받을 스레드
class ConnectThread extends Thread{
String hostname;
public ConnectThread(String addr){
hostname = addr;
}
public void run(){
try{
int port = 11001;
//소켓 생성
Socket socket =
new Socket(hostname,port);
//데이터를 전송하귀 위한 스트림 생성
ObjectOutputStream oos =
new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("클라이언트가 전송하는 메시지");
oos.flush();
//서버로부터 하나의 객체를 전송받기 위한 스트림
ObjectInputStream ois =
new ObjectInputStream(socket.getInputStream());
mes = ois.readObject().toString();
handler.sendEmptyMessage(0);
socket.close();
}catch(Exception e){
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText)findViewById(R.id.input01);
Button btn = (Button)findViewById(R.id.button01);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ConnectThread th = new ConnectThread("127.0.0.1");
th.start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
20141112_socket.zip