티스토리 뷰

개발/개발 자료

(Android) 소켓통신 예제

시원한물냉 2015. 1. 14. 13:24

서버 (Java Project)

public class ServerTest {

public static void main(String[] args) throws IOException{

ServerSocket serverSocket = null;

Socket clientSocket = null;

PrintWriter out = null;

BufferedReader in = null;

serverSocket = new ServerSocket(5555);

try {

clientSocket = serverSocket.accept();

System.out.println("Client connect");

out = new PrintWriter(clientSocket.getOutputStream(), true);

in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

while (true) {

String inputLine = null;

inputLine = in.readLine();

System.out.println("클라이언트로부터 받은 문자열 : " + inputLine);

out.println(inputLine);

if (inputLine.equals("quit"))

break;

}

out.close();

in.close();

clientSocket.close();

serverSocket.close();

} catch (Exception e){

e.printStackTrace();

}

}


}



클라이언트 (Android Project)

public class MainActivity extends Activity {

private Socket socket;

BufferedReader socket_in;

PrintWriter socket_out;

EditText input;

Button button;

TextView output;

String data;


@Override

public void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

input = (EditText) findViewById(R.id.input);

button = (Button) findViewById(R.id.button);

output = (TextView) findViewById(R.id.output);

button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

String data = input.getText().toString();

if(data != null) {

socket_out.println(data);

}

}

});

Thread worker = new Thread() {

public void run() {

try {

socket = new Socket("222.104.147.163", 5555);

socket_out = new PrintWriter(socket.getOutputStream(), true);

socket_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

} catch (IOException e) {

e.printStackTrace();

}

try {

while (true) {

data = socket_in.readLine();

output.post(new Runnable() {

public void run() {

output.setText(data);

}

});

}

} catch (Exception e) {

}

}

};

worker.start();

}


@Override

protected void onStop() {

// TODO Auto-generated method stub

super.onStop();

try {

socket.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}



댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함