티스토리 뷰
서버 (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(); } }
} |
'개발 > 개발 자료' 카테고리의 다른 글
(Android) java.lang.OutOfMemoryError 메모리부족.. (0) | 2015.01.14 |
---|---|
(Android) 소켓통신 예제, 안드로이드 채팅만들기 (3) | 2015.01.14 |
(Android) Thread 간단예제 (0) | 2015.01.14 |
(Android) Android Studio 기초 및 설치 (0) | 2015.01.14 |
(Android) Dx warning: Ignoring InnerClasses attribute for an anonymous inner class (0) | 2015.01.01 |