Riucc's Storage
RSS
태그
관리
쓰기
카테고리
  • IT (593)
    • 정리 (0)
    • C# (42)
    • ASP.NET MVC (16)
    • JQuery&Javascript (12)
    • CSS (11)
    • 데이터베이스 (32)
    • Windows Server (6)
    • Active Directory (3)
    • Exchange (9)
    • JAVA (2)
    • JSP (39)
    • JSP 게시판 만들기 (21)
    • JSP 개발 참고 (15)
    • JSP 안드로이드 (4)
    • Servlet (17)
    • Spring (42)
    • HTML (14)
    • NodeJS (46)
    • MongoDB (11)
    • 리눅스 (18)
    • 자료구조 (16)
    • 아이폰 (24)
    • 안드로이드 (68)
    • API 활용하기 (10)
    • 소켓네트워크 (28)
    • 라즈베리파이 (11)
    • AWS클라우드 (10)
    • 빅데이터Hadoop (22)
    • 커널모듈프로그래밍 (8)
    • 기타 (10)
    • 자격증 (26)
Riucc's Storage

[소켓네트워크] - 채팅 클라이언트 안드로이드용

소켓네트워크|2017. 6. 2. 00:12
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 ○ 채팅 클라이언트 안드로이드용

 

- AndroidManifest.xml - 아래 구문을 추가

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

 

- activity_main.xml - 

 

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.riu.chatclient.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="IP"
                android:textColor="#000000"
                android:textSize="20sp"
                android:gravity="center"/>
            <EditText
                android:id="@+id/ip_EditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="IP 입력"
                android:layout_weight="1"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Port" android:textColor="#000000"
                android:textSize="20sp"
                android:gravity="center"
                android:layout_weight="1"/>

            <EditText
                android:id="@+id/port_EditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="PORT 입력"
                android:layout_weight="1"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="닉네임" android:textColor="#000000"
                android:textSize="20sp"
                android:gravity="center"
                android:layout_weight="2"/>
            <EditText
                android:id="@+id/port_NameText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="닉네임 입력"
                android:layout_weight="1"/>
        </LinearLayout>
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" >

        <Button
            android:id="@+id/connect_Button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="연결" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/showText_TextView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text=""
                android:textColor="#000000"/>
        </ScrollView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/editText_massage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:ems="10"
            android:hint="채팅 메시지 입력" />

        <Button
            android:id="@+id/Button_send"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="전송" />
    </LinearLayout>

</LinearLayout>

 

- MainActivity.java -

 

package com.example.riu.chatclient;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.LinkedList;

public class MainActivity extends AppCompatActivity {

    TextView showText;
    Button connectBtn;
    Button Button_send;
    EditText ip_EditText;
    EditText port_EditText;
    EditText port_NameText;
    EditText editText_massage;
    Handler msghandler;

    SocketClient client;
    ReceiveThread receive;
    SendThread send;
    Socket socket;
    String nickname ="";
    LinkedList<SocketClient> threadList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ip_EditText = (EditText) findViewById(R.id.ip_EditText);
        port_EditText = (EditText) findViewById(R.id.port_EditText);
        connectBtn = (Button) findViewById(R.id.connect_Button);
        showText = (TextView) findViewById(R.id.showText_TextView);
        editText_massage = (EditText) findViewById(R.id.editText_massage);
        Button_send = (Button) findViewById(R.id.Button_send);
        port_NameText = (EditText)findViewById(R.id.port_NameText);
        threadList = new LinkedList<MainActivity.SocketClient>();
        this.setTitle("채팅서버 클라이언트_안드로이드");

        // ReceiveThread를통해서 받은 메세지를 Handler로 MainThread에서 처리(외부Thread에서는 UI변경이불가)
        msghandler = new Handler() {
            @Override
            public void handleMessage(Message hdmsg) {
                if (hdmsg.what == 1111) {
                    showText.append(hdmsg.obj.toString() + "\n");
                }
            }
        };

        // 연결버튼 클릭 이벤트
        connectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //Client 연결부
                nickname = port_NameText.getText().toString();
                client = new SocketClient(ip_EditText.getText().toString(),
                        port_EditText.getText().toString());
                threadList.add(client);
                client.start();
            }
        });

        //전송 버튼 클릭 이벤트
        Button_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                //SendThread 시작
                if (editText_massage.getText().toString() != null) {
                    send = new SendThread(socket);
                    send.start();

                    //시작후 edittext 초기화
                    editText_massage.setText("");
                }
            }
        });
    }

    class SocketClient extends Thread {
        boolean threadAlive;
        String ip;
        String port;

        DataOutputStream output = null;

        public SocketClient(String ip, String port) {
            threadAlive = true;
            this.ip = ip;
            this.port = port;
        }

        @Override
        public void run() {

            try {
                // 연결후 바로 ReceiveThread 시작
                socket = new Socket(ip, Integer.parseInt(port));
                output = new DataOutputStream(socket.getOutputStream());
                receive = new ReceiveThread(socket);
                receive.start();

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

    class ReceiveThread extends Thread {
        private Socket sock = null;
        DataInputStream input;

        public ReceiveThread(Socket socket) {
            this.sock = socket;
            try{
                input = new DataInputStream(sock.getInputStream());
            }catch(Exception e){
            }
        }
        // 메세지 수신후 Handler로 전달
        public void run() {
            try {
                while (input != null) {
                    String msg;
                    int count = input.available();
                    byte[] rcv = new byte[count];
                    input.read(rcv);
                    msg = new String(rcv);

                    if (count > 0) {
                        Log.d(ACTIVITY_SERVICE, "test :" +msg);
                        Message hdmsg = msghandler.obtainMessage();
                        hdmsg.what = 1111;
                        hdmsg.obj = msg;
                        msghandler.sendMessage(hdmsg);
                        Log.d(ACTIVITY_SERVICE,hdmsg.obj.toString());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class SendThread extends Thread {
        Socket socket;
        String sendtmp=  editText_massage.getText().toString();
        String sendmsg = "["+nickname+"] " + sendtmp +"\n";
        DataOutputStream output;

        public SendThread(Socket socket) {
            this.socket = socket;
            try {
                output = new DataOutputStream(socket.getOutputStream());
            } catch (Exception e) {
            }
        }

        public void run() {

            try {
                // 메세지 전송부
                Log.d(ACTIVITY_SERVICE, "11111");

                if (output != null) {
                    if (sendmsg != null) {
                        output.write(sendmsg.getBytes());

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

            }
        }
    }
} 

 

 

 

 

'소켓네트워크' 카테고리의 다른 글

[소켓네트워크] - html 요청 라인 vs 상태 라인  (0) 2017.06.11
[소켓네트워크] - 채팅 클라이언트 MFC용  (0) 2017.06.02
[소켓네트워크] - 채팅 서버 코드  (1) 2017.06.02
[소켓네트워크] - strtok 이용한 문자열 분리  (0) 2017.05.05
[소켓네트워크] - 일반 소켓 vs RAW 소켓  (0) 2017.04.21

댓글()
카테고리
  • IT (593)
    • 정리 (0)
    • C# (42)
    • ASP.NET MVC (16)
    • JQuery&Javascript (12)
    • CSS (11)
    • 데이터베이스 (32)
    • Windows Server (6)
    • Active Directory (3)
    • Exchange (9)
    • JAVA (2)
    • JSP (39)
    • JSP 게시판 만들기 (21)
    • JSP 개발 참고 (15)
    • JSP 안드로이드 (4)
    • Servlet (17)
    • Spring (42)
    • HTML (14)
    • NodeJS (46)
    • MongoDB (11)
    • 리눅스 (18)
    • 자료구조 (16)
    • 아이폰 (24)
    • 안드로이드 (68)
    • API 활용하기 (10)
    • 소켓네트워크 (28)
    • 라즈베리파이 (11)
    • AWS클라우드 (10)
    • 빅데이터Hadoop (22)
    • 커널모듈프로그래밍 (8)
    • 기타 (10)
    • 자격증 (26)
최근 등록 현황
최근 글
최근 월별 글
최근 댓글
최근 글
최근 월별 글
최근 댓글
최근 글
최근 월별 글
최근 댓글
달력
지난달
2026.1
다음달
일월화수목금토
123
45678910
11121314151617
18192021222324
25262728293031
태그 구름
  • 안드로이드 카카오 로그인 연동
  • 정보처리산업기사 16년
  • 정규형
  • jsp
  • nodejs express
  • 정규화
  • 리눅스
  • 정보처리산업기사 16년 필기
  • 커널 모듈 프로그래밍
  • 안드로이드
  • 정보처리산업기사 15년 필기
  • 정보처리산업기사 필기 정리
  • 안드로이드 intent
  • nodejs MySQL 연동하기(Connection Pool)
  • 자료구조
  • 데이터베이스
  • 소켓
  • 정보처리기사 실기 정리
  • 정보처리산업기사 필기
  • 카카오 로그인 연동
  • 이클립스 mysql 연동
  • 카카오 로그인
  • HTML
  • 안드로이드 카카오 로그인
  • 정보처리산업기사 정리
  • 이클립스 디비 연동
  • 정보처리산업기사 요약
  • 정보처리산업기사 총정리
  • 소켓 프로그래밍
  • 정보처리산업기사 15년
카운터
전체 방문자
오늘
어제
Skin by M1REACT. Designed by M1STORY.TISTORY.COM. Valid XHTML 1.0 and CSS 3. Copyright ⓒ Riucc's Storage. All rights reserved.

티스토리툴바