android socket 编程

一、需要注意的地方:

1.需要添加网络权限:<uses-permission android:name="android.permission.INTERNET" />;

2.android4.0平台默认不允许在主线程中进行网络访问,所以要新建thread来运行socket读写的程序;

 

二、tcp socket 通讯示例

package test.dxp.sockets;

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;
import java.net.SocketException;
import java.net.UnknownHostException;

import test.dxp.sockets.R;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Socket_testActivity extends Activity implements OnClickListener{
 private String TAG = "TEST_SOCKET";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btnStartDec = (Button)findViewById(R.id.startDec);
        Button btnStopDec = (Button)findViewById(R.id.stopDec);  
        btnStartDec.setOnClickListener(this);
        btnStopDec.setOnClickListener(this);
    }
    private int startDec()
    {
     Log.d(TAG,"startDec");
     
     service_start();
     client_start();
     return 0;
    }
    private int stopDec()
    {
     Log.d(TAG,"stopDec");
     service_stop();
     client_stop();
     return 0;
    }

 public void onClick(View v) {

  switch (v.getId()) {
  case R.id.startDec:
   
   startDec();
   break;
  case R.id.stopDec:

   stopDec();
   break;

  default:
   break;
  }
  
 }
 ServerSocket sever;
 private void service_start()
 {
  
  int port = 12345;
  
  Log.d(TAG,"service start 1");
        try {
              //创建一个ServerSocket对象,并让这个Socket在4567端口监听
         sever = new ServerSocket(port);       

           } catch (IOException e) {

              // TODO Auto-generated catch block
              e.printStackTrace();
          }
        Log.d(TAG,"service start 2");
        beginListen();
        Log.d(TAG,"service start 3");

 }
 private void service_stop() {
  Log.d(TAG,"service stop 1");
  try{
   sever.close();
  }catch(IOException e){
            e.printStackTrace();
        }
  Log.d(TAG,"service stop 2");
 }
 Socket socket;
 public void beginListen(){
  
   Log.d(TAG,"service listen 1");
   
   new Thread(new Runnable(){
    public void run(){
      BufferedReader in;
      try{
       socket = sever.accept();
      }catch(SocketException e){
       e.printStackTrace();
      }catch (IOException e){
       e.printStackTrace();
      }
      
      Log.d(TAG,"service listen 2");
            try{
                in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
                PrintWriter out = new PrintWriter(socket.getOutputStream());
                while (!socket.isClosed()){
                    String str;
                    str = in.readLine();
                    System.out.println("socket service:");
                    out.println("hello! " + str);
                    out.flush();
                    if (str == null || str.equals("end"))
                        break;
                    System.out.println(str);
                }
                socket.close();
            }catch(IOException e){
                e.printStackTrace();
            }
    }
   }
   
   ).start();
  
 }
 
          
 static Socket client;
 private void client_start()
 {
  new Thread(new Runnable(){
   public void run(){
    try{
     client = new Socket("127.0.0.1",12345);
    }catch (UnknownHostException e){
     e.printStackTrace();
    }catch (IOException e){
     e.printStackTrace();
    }
    System.out.println("socket client:");
    System.out.println(sendMsg("nimei1111"));
          
   }
  }
  
  ).start();
    

 }
 private void client_stop() {
  try{
   client.close();
  }catch(IOException e){
            e.printStackTrace();
        }
 }
 public String sendMsg(String msg){
  try{
   BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
   PrintWriter out = new PrintWriter(client.getOutputStream());
   out.println(msg);
   out.flush();
   return in.readLine();
  }catch(IOException e){
   e.printStackTrace();
  }
  return "";
 }
   
}

 

 

你可能感兴趣的:(thread,android,socket,String,service,button)