이건 JAVA project 
 ChatServer.class
package chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {


	int PORT=5000;

	public ChatServer(){//default Construtor
		System.out.println("시작");
		try {

			//1.서버소켓을 생성한다. port
			ServerSocket server = new ServerSocket(PORT);
			System.out.println("서버생성 및 레디 상태");

			while(true){
				//2.서버소켓이 클라이언트가 접속할 수 있도록 ready
				Socket socket = server.accept();//accept에 block
				String who = socket.getInetAddress().getHostAddress();
				System.out.println("접속 IP: "+who);
				ClientThread thread= new ClientThread(socket);
				thread.start();
			}
		} catch (IOException e) {


			e.printStackTrace();
		}
	}
	  
	//클라이언트와 데이터를 주고 받는 기능을 담당
	class ClientThread extends Thread{
		Socket socket;
		BufferedReader br; //데이터 받을 때 사용
		PrintWriter pw;    //데이터 보낼 때 사용
		
		public ClientThread(Socket socket) {
			this.socket=socket;
			try {
				InputStream is = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(is);
				
				br = new BufferedReader(isr);
				pw = new PrintWriter(socket.getOutputStream());
				
				//Line 단위로 보냈으니 Line 단위로 읽자
				String firstMessage = br.readLine();
				System.out.println(firstMessage);
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		 
		@Override
		public void run() {
			super.run();
			try {
				String line="";
				while( (line = br.readLine()) !=null){
					System.out.println(line);
					send(line);
				}
			} catch (Exception e) {
			}
		}
		//데이터 보내는 메서드
		public void send(String line){
			pw.println(line);
			pw.flush();
		}
	}
	public static void main(String[] args) {
		new ChatServer();
	}
}



여기부터는 AndroidProject 

manifast.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.chatclient"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ChatClientActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />

    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
ChatClientActivity.java
package com.gusfree.chatclient;

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

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

public class ChatClientActivity extends Activity implements OnClickListener{

	TextView textView;
	EditText editText;
	private final int PORT=5000;
	private final String IP="ip를 적어주삼~";//cmd창에,ipconfig명령어 
	Socket socket;
	PrintWriter pw;    //데이터를 보낼 때 사용할 객체
	BufferedReader br; //데이터를 받을 때 사용할 객체

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		textView=(TextView) findViewById(R.id.textView1);
		editText=(EditText) findViewById(R.id.editText1);
		findViewById(R.id.button1).setOnClickListener(this);

		//서버와 Socket으로 연결하기
		try { 
			socket = new Socket(IP,PORT);//서버연결
			OutputStream os = socket.getOutputStream();
			pw = new PrintWriter(os);
			InputStream is = socket.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));
			
			/* 바이트 단위 전송
			 * pw.write("안녕? I'm Cityboy");
			 * pw.flush();    */
			
			//Line 단위 전송
			pw.println("hi? I'am kj");
			pw.flush();
			
			//서버로부터 오는 데이터를 받는 스레드 생성 + 실행
			new ReceiveThread().start();
			
		} catch (UnknownHostException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}
	//서버로 부터 오는 데이터를 받는 역활을 맡는다.
	class ReceiveThread extends Thread{
		String line;
		
		@Override
		public void run() {
			super.run();
			try {
				while( (line=br.readLine()) != null){
					/*주의: 스레드에서는 뷰에 접근할 수없다.*/
					
					//대안1:post 메서드 사용, 대안2:핸들러 사용
					textView.post(new Runnable() {
						@Override
						public void run() {
							String before = (String) textView.getText();
							textView.setText(line+"\n"+before);
						}
					});
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onClick(View v) {
		String msg = editText.getText().toString().trim();
		pw.println(msg);
		pw.flush();
	}
}







'Android > 2012.04월 강좌' 카테고리의 다른 글

13일차 Font  (0) 2012.05.14
12일차 SocketServer 2 (Client,Server C->C)  (0) 2012.05.11
11일차 Json  (0) 2012.05.10
11일차 NavarOpenAPI 이용한 Dom Parser  (0) 2012.05.10
11일차 DOM과 SAX의 기술적 특징  (0) 2012.05.10

+ Recent posts