Android 使用Socket進行服務(wù)器通信

·使用Socket進行簡單服務(wù)器通信
簡單服務(wù)器端:


public class ServerThread implements Runnable{
    Socket s=null;
    BufferedReader br=null;
    public ServerThread(Socket s) throws UnsupportedEncodingException, IOException {
        this.s=s;
        br=new BufferedReader(new InputStreamReader(s.getInputStream(), "utf-8"));
    }
    @Override
    public void run() {
        try{
            String content=null;
            while((content=readFromClient())!=null){
                for(Iterator<Socket>it=Myserver.socketList.iterator();it.hasNext();){
                    Socket s=it.next();
                    try{
                        OutputStream os=s.getOutputStream();
                        os.write((content+"\n").getBytes("utf-8"));
                    }catch(SocketException e){
                        e.printStackTrace();
                        it.remove();
                        System.out.println(Myserver.socketList);
                    }
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    private String readFromClient(){
        try{
            return br.readLine();
        }catch(IOException e){
            e.printStackTrace();
            Myserver.socketList.remove(s);
        }
        return null;
    }
}
public class Myserver {
    public static ArrayList<Socket>socketList=new ArrayList<Socket>();
    public static void main(String[] args) throws IOException {
        ServerSocket ss=new ServerSocket(31510);
        while(true){
            Socket s=ss.accept();
            socketList.add(s);
            new Thread(new ServerThread(s)).start();
        }
    }
}

android應(yīng)用端:

public class ClientThread implements Runnable{
    private Socket s;
    //發(fā)送,接受UI線程信息的Handler對象
    private Handler handler;
    public Handler revHandler;
    BufferedReader br=null;
    OutputStream os=null;
    //構(gòu)造函數(shù)
    public ClientThread(Handler handler){
        this.handler=handler;
    }
    @Override
    public void run() {
        try{
            s=new Socket("222.26.207.88",31510);
            //輸入流將Socket讀入BufferedReader
            br=new BufferedReader(new InputStreamReader(s.getInputStream()));
            os=s.getOutputStream();
            new Thread(){
                public void run() {
                    String content=null;
                    try{
                        while((content=br.readLine())!=null){
                            Message msg=new Message();
                            msg.what=0x123;
                            //將BufferedREader中的數(shù)據(jù)讀入content后加入message
                            msg.obj=content;
                            //通過handler發(fā)送消息至消息隊列
                            handler.sendMessage(msg);
                        }
                    }
                    catch(IOException e){
                            e.printStackTrace();
                    }
                }
            }.start();
            //初始化Looper
            Looper.prepare();
            revHandler=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    //接收到UI線程中用戶輸入的數(shù)據(jù)
                    if(msg.what==0x345){
                        try{
                            //將用戶在文本框的內(nèi)容寫入網(wǎng)絡(luò)
                            os.write((msg.obj.toString()+"\r\n").getBytes("utf-8"));
                        }
                        catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            };
            //啟動Looper
            Looper.loop();
        }catch(SocketException e){
            System.out.println("超時");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

public class MainActivity extends Activity {
    EditText input;
    TextView show;
    Button send;
    Handler handler;
    //與服務(wù)器通信的子線程
    ClientThread clientThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        input=(EditText)findViewById(R.id.input);
        show=(TextView)findViewById(R.id.show);
        send=(Button)findViewById(R.id.send);
        //將子線程中的內(nèi)容顯示在文本框
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what==0x123){
                    show.append("\n"+msg.obj.toString());
                }
                super.handleMessage(msg);
            }
        };
        clientThread=new ClientThread(handler);
        //讀取來自服務(wù)器的數(shù)據(jù)
        new Thread(clientThread).start();
        send.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                try{
                    Message msg=new Message();
                    msg.what=0x345;
                    msg.obj=input.getText().toString();
                    clientThread.revHandler.sendMessage(msg);
                    input.setText("");
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容