Serverandroid app간에 데이터를 주고 받는 작업이 필요하여 간단하게 샘플 작업을 해보았습니다인터넷에 많은 예제가 널려 있는데 하나 더 던져 봅니다.  IPPC에 설정된 것으로 사용을 하기 위해 PC에 설정된(자동으로 잡히도록 되어 있으므로 다음에는 변할 수 있지만) 값을 찾아 봅니다.  ipconfig/all 명령으로 찾으면 됩니다.


andriod eclipse socket


 

1. Eclipse Server

 

서버에서는 IP는 사용하지 않고 port 번호만으로 접속 대기 상황을 만들면 됩니다그리고 client에서 연결 요청과 데이터가 들어오면 다시 보내주는 작업을 진행 합니다.

 

//client 접속 대기

Socket client = serverSocket.accept();

//client data 수신

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

String str = in.readLine();

//client 다시 전송

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

out.println("Server Received : '" + str + "'");

 

2. Android Client

 

Client 에서는 화면작업이 좀 있습니다그리고 문자를 입력 받아 서버에 보내주고 다시 받아오는 작업을 진행 합니다.

 

//소켓 생성
InetAddress serverAddr = InetAddress.getByName(ip);
 
socket =  new Socket(serverAddr,port);
//입력 메시지
String sndMsg = et.getText().toString();
//데이터 전송
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(sndMsg);
//데이터 수신
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String read = input.readLine();

 

그리고 인터넷을 사용하므로 Manifest.xml에 권한 설정을 해주면 됩니다.

 

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

 

  

3. 결과 화면

 

안드로이드 클라이언트 화면입니다문자 입력과 전송버튼 그리고 서버로 부터 받은 데이터를 화면에 출력하는 기능이 있습니다.


andriod eclipse socket


이런... Connet 버튼은 테스트하려고 만들었는데 사용하지 않습니다삭제 안했네요.

 

서버쪽은 클라이언트에서 보내온 데이터를 콘솔에 출력만 합니다.


andriod eclipse socket


소스가 간단해서 설명도 간단 하네요.

 

4. 전체 소스

 

4.1 Eclipse Server

 

package egovframework.admin.chart.web;

 

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.ObjectOutputStream;

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

 

public class TCPServer implements Runnable {

 

             public static final int ServerPort = 9999;

//    public static final String ServerIP = "192.168.0.6";

 

             @Override

             public void run() {

                           try {

            System.out.println("Connecting...");

            ServerSocket serverSocket = new ServerSocket(ServerPort);

 

            while (true) {

                     //client 접속 대기

                Socket client = serverSocket.accept();

                System.out.println("Receiving...");

                try {

                   //client data 수신

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

                    String str = in.readLine();

                    System.out.println("Received: '" + str + "'");

                    //client에 다시 전송

                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

                    out.println("Server Received : '" + str + "'");

                   

                } catch (Exception e) {

                    System.out.println("Error");

                    e.printStackTrace();

                } finally {

                    client.close();

                    System.out.println("Done.");

                }

            }

        } catch (Exception e) {

            System.out.println("S: Error");

            e.printStackTrace();

        }

             }

            

             public static void main(String[] args) {

        Thread ServerThread = new Thread(new TCPServer());

        ServerThread.start();

     }

}

 

4.2 안드로이드 Client

 

activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
   
tools:context=".MainActivity">

    <
TextView
       
android:id="@+id/TextView01"
       
android:layout_width="fill_parent"
       
android:layout_height="wrap_content" />

    <
EditText
       
android:id="@+id/EditText01"
       
android:layout_width="289dp"
       
android:layout_height="wrap_content"
       
android:layout_marginStart="92dp"
       
app:layout_constraintStart_toStartOf="@+id/Button01"
       
tools:layout_editor_absoluteY="0dp" />

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

    <
Button
       
android:id="@+id/button02"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginEnd="16dp"
       
android:layout_marginTop="456dp"
       
android:text="Connect"
       
app:layout_constraintEnd_toEndOf="parent"
       
app:layout_constraintTop_toTopOf="parent" />

    <
TextView
       
android:id="@+id/chatTV"
       
android:layout_width="fill_parent"
       
android:layout_height="381dp"
       
android:layout_marginTop="64dp"
       
app:layout_constraintTop_toTopOf="@+id/TextView01"
       
tools:layout_editor_absoluteX="0dp" />
</
android.support.constraint.ConstraintLayout>

 

 

AndroidManifest.xml

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    
package="com.example.tcpclient">

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

    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:roundIcon="@mipmap/ic_launcher_round"
       
android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

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

</
manifest>

 

 

MainActivity.java


package com.example.tcpclient;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;


public class MainActivity extends AppCompatActivity {

   
private Handler mHandler;
    Socket
socket;
   
private String ip = "192.168.0.6"; // IP 주소
   
private int port = 9999; // PORT번호
   
EditText et;
    TextView
msgTV;

   
@Override
   
protected void onStop() {
       
super.onStop();
       
try {
           
socket.close();
        }
catch (IOException e) {
            e.printStackTrace();
        }
    }

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

       
mHandler = new Handler();

       
et = (EditText) findViewById(R.id.EditText01);
        Button btn = (Button) findViewById(R.id.
Button01);
        Button btnCon = (Button)findViewById(R.id.
button02);
       
final TextView tv = (TextView) findViewById(R.id.TextView01);
       
msgTV = (TextView)findViewById(R.id.chatTV);

        btn.setOnClickListener(
new View.OnClickListener() {
           
public void onClick(View v) {
               
if (et.getText().toString() != null || !et.getText().toString().equals("")) {
                    ConnectThread th =
new ConnectThread();
                    th.start();
                }
            }
        });
    }

   
class ConnectThread extends Thread{
       
public void run(){
           
try{
               
//소켓 생성
               
InetAddress serverAddr = InetAddress.getByName(ip);
                
socket new Socket(serverAddr,port);
               
//입력 메시지
               
String sndMsg = et.getText().toString();
                Log.d(
"=============", sndMsg);
               
//데이터 전송
               
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                out.println(sndMsg);
               
//데이터 수신
               
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String read = input.readLine();
               
//화면 출력
               
mHandler.post(new msgUpdate(read));
                Log.d(
"=============", read);
               
socket.close();
            }
catch(Exception e){
                e.printStackTrace();
            }
        }
    }
   
// 받은 메시지 출력
   
class msgUpdate implements Runnable {
       
private String msg;
       
public msgUpdate(String str) {
           
this.msg = str;
        }
       
public void run() {
           
msgTV.setText(msgTV.getText().toString() + msg + "\n");
        }
    };
}

 

- copy coding -


+ Recent posts