Android Socket 사용법 간단하게 배우 기
먼저 여러분 께 응용 프로그램의 인 터 페 이 스 를 보 여 드 리 면 대체적인 기능 을 기본적으로 알 수 있 습 니 다.
 
  activity_main.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity">
 <EditText
 android:id="@+id/editText"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="         "/>
 
 <Button
 android:id="@+id/button01"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="  "/>
 <Button
 android:id="@+id/button02"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="  "/>
 <ScrollView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:scrollbars="vertical"
 android:fadingEdge="vertical">
 <TextView
  android:id="@+id/textView"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="    :"/>
 </ScrollView>
</LinearLayout>
다음은 서버 와 클 라 이언 트 가 필요 합 니 다.서버,저 는 Eclipse 가 쓴 자바 서버 를 사용 합 니 다.클 라 이언 트,저 는 Android Studio 로 썼 습 니 다.
package com.ryan.socketdemo01;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
/**
 *      :            (      )
 *
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
 private Button button01 = null;
 private Button button02 = null;
 private EditText editText = null;
 private TextView textView = null;
 private static Socket ClientSocket = null;
 private byte[] msgBuffer = null;
 Handler handler = new Handler();
 private void initView() {
 button01 = (Button) findViewById(R.id.button01);
 button02 = (Button) findViewById(R.id.button02);
 editText = (EditText) findViewById(R.id.editText);
 textView = (TextView) findViewById(R.id.textView);
 button01.setOnClickListener(this);
 button02.setOnClickListener(this);
 button01.setEnabled(true);
 button02.setEnabled(false);
 }
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 initView();
 }
 @Override
 public void onClick(View v) {
 switch (v.getId()){
  case R.id.button01:
  // TODO: 15-9-4 socket    
  connectThread();
  break;
  case R.id.button02:
  // TODO: 15-9-4       
  sendMsgThread();
  break;
 }
 }
 private void sendMsgThread() {
 final String text = editText.getText().toString();
 try {
  msgBuffer = text.getBytes("UTF-8");
 } catch (UnsupportedEncodingException e) {
  e.printStackTrace();
 }
 new Thread(new Runnable() {
  @Override
  public void run() {
  try {
   OutputStream outputStream;
   //Socket   
   outputStream = ClientSocket.getOutputStream();
   outputStream.write(msgBuffer);
   outputStream.flush();
   outputStream.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  handler.post(new Runnable() {
   @Override
   public void run() {
   textView.append("    :"+text+"
");
   }
  });
  }
 }).start();
 }
 private void connectThread() {
 new Thread(new Runnable() {
  @Override
  public void run() {
  try {
   ClientSocket = new Socket("10.0.2.2",9001);
   if (ClientSocket.isConnected()){
   handler.post(new Runnable() {
    @Override
    public void run() {
    textView.append("    !"+"
");
    button01.setEnabled(false);
    button02.setEnabled(true);
    }
   });
   }else {
   handler.post(new Runnable() {
    @Override
    public void run() {
    textView.append("    !"+"
");
    }
   });
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
 }).start();
 }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.menu_main, menu);
 return true;
 }
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 // Handle action bar item clicks here. The action bar will
 // automatically handle clicks on the Home/Up button, so long
 // as you specify a parent activity in AndroidManifest.xml.
 int id = item.getItemId();
 //noinspection SimplifiableIfStatement
 if (id == R.id.action_settings) {
  return true;
 }
 return super.onOptionsItemSelected(item);
 }
}
new Thread (new Runnable) {
 @Override
 public void run() {
 } 
} 
그리고 하위 스 레 드 가 주 UI 를 업데이트 하 는 방법 은 다음 과 같 습 니 다.
제 가 사용 하 는 것 은 Handler.post()입 니 다.마찬가지 로 매우 간단 한 사용 방법.
Handler handler = new Handler(); 
handler.post(new Runnable() {
   @Override
   public void run() {
   textView.append("    :"+text+"
");
   }
  });
 
그리고 I/O 흐름 조작 에 관 한 방법 입 니 다.
여 기 는 제 가 상세 한 소 개 를 하지 않 겠 습 니 다.여러분 스스로 구 글 하 세 요!뭐 공부 해요?직접 FQ 도 구 를 찾 아 보 세 요~
여기 서 I/O 에 대한 간단 한 사용법 을 말씀 드 리 겠 습 니 다.
만물 은 최초의'InputStream,OutputStream'에서 시 작 됩 니 다.그의 방법 은 reader()와 write()밖 에 없습니다.그 위 에 있 는 것,예 를 들 어 가장 많이 사용 하 는 버 프 레 드 리더 대상 은 모두 그 위 에 있 는 업그레이드 포장 으로 옷 을 입고 더욱 화려 해 졌 을 뿐이다.그의 전문 용 어 는 바로 장식 자 모델 로 관심 이 있 는 것 은 자 료 를 뒤 져 볼 수 있다.
 
 처음에 저 는 InputStream 과 OutputStream 의 방법 에 대해 잘 몰 랐 습 니 다.InputStream 을 write()방법 으로 잘못 사용 하 는 경우 가 많 았 습 니 다.어디서 이런 말 을 보 았 는 지 모 르 겠 습 니 다.I/O 흐름 의 조작 은 실질 적 으로 Socket,ServerSocket 연결 후 발생 하 는 데이터 흐름 관 입 니 다.reader 와 write 는 읽 기와 쓰기 라 는 뜻 으로 그 데이터 흐름 관 에 비해 작 동 합 니 다.파이프 에 있 는 정 보 를 읽 고 파이프 에 정 보 를 기록 하 는 것 이다.이러 면 다 들 움 직 일 지 모 르 겠 네.
마지막 으로 우리 가 배 워 야 할 Socket 이다.
그의 사용 도 간단 하 다.Socket 대상 을 만 들 고 IP 와 포트 를 설정 하여 I/O 흐름 을 얻는다.
ClientSocket = new Socket("10.0.2.2",9001);
outputStream = ClientSocket.getOutputStream();
내 가 그 중에서 만난 문 제 를 말 해 봐.
1.시 뮬 레이 터 가 자바 서버 에 연결 되 지 않 습 니 다.IP 설정 이 잘못 되 었 습 니 다.제 가 처음에 설정 한 Ip 는 127.0.0.1 입 니 다.해 결 된 연결:
http://stackoverflow.com/questions/8191192/reaching-a-network-device-by-ip-and-port-using-the-android-emulator/8191487#8191487
http://stackoverflow.com/questions/10336637/how-do-i-socket-an-android-program-to-a-localhost-server
2.manifest 설정 을 잊 어 버 리 거나 시스템 에서 제공 하 는 android.permission.INTERNET 은 모두 대문자 입 니 다!!말하자면 우 스 꽝 스 럽 지만 저 는 이런 문제 에 부 딪 혔 습 니 다.시스템 이 자동 으로 완성 하 는 코드 힌트 는 모두 대문자 입 니 다.저 는 그런 줄 알 았 습 니 다.결 과 는 분명히 소문 자일 것 입 니 다.
자바 서버 코드 를 붙 이 는 것 을 잊 어 버 렸 습 니 다.보충 하 세 요.
/**
 *      :          
 */
public class Main {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    new SerVerListener().start();
  }
}
 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
public class SerVerListener extends Thread{
  
  private Socket clientSocket = null;
  private ServerSocket serverSocket = null;
  private InputStream inputStream = null;
  private byte[] buffer = null;
  
  @Override
  public void run() {
    // TODO Auto-generated method stub
    
    try {
      serverSocket = new ServerSocket(9001);
      System.out.println("     ,     〜〜");
      //block
      clientSocket = serverSocket.accept();
      System.out.println("      ");
      inputStream = clientSocket.getInputStream();
      
      BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
      String str;
      
      while((str = br.readLine())!= null){
        System.out.println(str);
      }
      
    }catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      try {
        inputStream.close();
        serverSocket.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    
    
  }
}
 
 OK,기본적으로 이렇다.
이상 은 본문의 전체 내용 이 므 로 여러분 의 학습 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.