Android之Socket简单使用

效果图(这里是自己发给自己)

Android之Socket简单使用_第1张图片

服务器端代码:MySocketServer.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MySocketServer {
    private ServerSocket socket=null;
    private static final int PORT=9999;
    private ExecutorService execut=null;
    private List myData;
    public static void main(String[] args) {
        new MySocketServer();
    }
    public MySocketServer(){
        myData=new ArrayList();
        execut=Executors.newCachedThreadPool();
        try {
            socket=new ServerSocket(PORT);
            System.out.println("服务器已启动......");
            Socket client=null;
            while(true){
                client=socket.accept();
                myData.add(client);
                execut.execute(new Service(client));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public class Service implements Runnable{
        private Socket socket;
        private BufferedReader in=null;
        private String msg;
        public Service(Socket sk){
            this.socket=sk;
            try {
                in=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
                msg="新连接地址:"+socket.getInetAddress();
                System.out.println(msg);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    if((msg=in.readLine())!=null){
                        if(msg.equals("close")){
                            in.close();
                            socket.close();
                            break;
                        }else{
                            msg+="\t"+socket.getInetAddress()+"在发给你";
                            sendMsg();
                            System.out.println(msg);
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        public void sendMsg(){
            int num=myData.size();
            for(int i=0;inull;
                try {
                    out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(),"utf-8")),true);
                    out.println(msg);
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }
}

客户端代码:MainActivity.java

package com.example.ygd.mymaterialtest;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends Activity implements Runnable{
    private EditText et;
    private Button bt;
    private TextView tv;
    private static final String Host="172.20.10.3";
    private static final int PORT=9999;
    private Socket socket=null;
    private BufferedReader in=null;
    private PrintWriter out=null;
    private String content="";
    Handler mHandler=new Handler(){
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            Bundle bundle=msg.getData();
            String cont=bundle.getString("content");
            tv.setText(cont);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et= (EditText) findViewById(R.id.et);
        bt= (Button) findViewById(R.id.bt);
        tv= (TextView) findViewById(R.id.tv);

        if(Build.VERSION.SDK_INT>9){
            StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        try {
            socket=new Socket(Host,PORT);
            in=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
            out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8")),true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg=et.getText().toString();
                if(socket.isConnected()){
                    if(!socket.isOutputShutdown()){
                        out.println(msg);
                    }
                }
            }
        });
        new Thread(this).start();

    }

    @Override
    public void run() {
        while(true){
            if(!socket.isClosed()){
                if(socket.isConnected()){
                    if(!socket.isInputShutdown()){
                        try {
                            if((content=in.readLine())!=null){
                                content+="\n";
                                Message msg=new Message();
                                Bundle bundle=new Bundle();
                                bundle.putString("content",content);
                                msg.setData(bundle);
                                mHandler.sendMessage(msg);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

你可能感兴趣的:(安卓学习)