Android 채팅 소스 03

Programming/Android 2013. 8. 20. 17:58 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package com.tistory.tansanc.Test130805;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	String msg;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		MessageReceiveThread mrt = new MessageReceiveThread();
		mrt.start();
	}

	public void mOnClick(View v) {
		EditText editText1 = (EditText) findViewById(R.id.editText1);
		msg = editText1.getText().toString();
		MessageSendThread mst = new MessageSendThread();
		mst.start();
	}

	class MessageReceiveThread extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub

			Socket socket = null;
			PrintWriter out = null;
			BufferedReader in = null;

			try {
				socket = new Socket("115.20.247.141", 2013);
				out = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream(), "utf-8"), true);
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream(), "utf-8"));
				
				while(true)
				{
					String receiveString = in.readLine();
					Message message = new Message();
					message.obj = receiveString;
					mHandler.sendMessage(message);
				}
			} catch (UnknownHostException e) {
			} catch (IOException e) {
			}

			super.run();
		}
	}

	class MessageSendThread extends Thread {
		public void run() {
			Socket socket = null;
			PrintWriter out = null;
			BufferedReader in = null;

			try {
				socket = new Socket("115.20.247.141", 2013);
				out = new PrintWriter(new OutputStreamWriter(
						socket.getOutputStream(), "utf-8"), true);
				in = new BufferedReader(new InputStreamReader(
						socket.getInputStream(), "utf-8"));

				out.println(msg);

				out.close();
				in.close();
				socket.close();
			} catch (UnknownHostException e) {
			} catch (IOException e) {
			}
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String receiveString = (String) msg.obj;
			TextView textView1 = (TextView) findViewById(R.id.textView1);
			textView1.setText(textView1.getText() + "\n" + receiveString);
		}
	};
}


'Programming > Android' 카테고리의 다른 글

Android 채팅 소스 04  (0) 2013.08.21
Android 채팅 서버 소스 01  (0) 2013.08.20
Android 채팅 소스 02  (0) 2013.08.20
Android 채팅 소스 01  (0) 2013.08.20
Android Download html  (0) 2013.08.20