android多线程访问服务器数据

53 篇文章 0 订阅

android多线程访问服务器数据

使用多线程的方式访问网络资源。其中服务器能够读取到客户端发送的数据,同时把接受到的数据返回给客户端(也就是android)。android这边能够进行数据的发送和接受接受后能够把数据展现在界面上。这里需要注意的是,采用了Handler Message的方式进行。下面是服务器代码:
package com.xueyoucto.xueyou;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.BufferUnderflowException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * Hello world!
 */
class ServerThread implements Runnable {
    private Socket s = null;
    BufferedReader br = null;
    OutputStream outputStream = null;

    public ServerThread(Socket s) throws IOException {
        this.s = s;
        br = new BufferedReader(new InputStreamReader(s.getInputStream(), "utf-8"));
        outputStream = s.getOutputStream();
    }

    public void run() {
        String content = null;
        while((content = readFromClient()) != null){
            System.out.println("服务器收到内容:" + content);
            try {
                outputStream.write((content + "\r\n").getBytes("utf-8"));
                System.out.println("服务器发送内容:" + content);
            } catch (IOException e) {
                e.printStackTrace();
                App.socketList.remove(s);
            }
        }
    }
    public String readFromClient(){
        try {
            return br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            App.socketList.remove(s);
        }
        return null;
    }
}

public class App {
    private static final int SERVER_PORT = 61000;
    public static List<Socket> socketList = new ArrayList<Socket>();

    public static void main(String[] args) throws IOException {
        System.out.println("hello world");
        ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
        while (true) {
            Socket s = serverSocket.accept();
            System.out.println("someone in...");
            socketList.add(s);
            new Thread(new ServerThread(s)).start();
        }
    }
}

运行结果:


android代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.wuxueyou.myfirstandroidapplication.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="测试按钮"
        android:id="@+id/button"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="测试文本"
        android:id="@+id/textView2"
        android:layout_centerVertical="true"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignStart="@+id/button2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_below="@+id/button"
        android:layout_marginTop="59dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送"
        android:id="@+id/button2"
        android:layout_below="@+id/textView2"
        android:layout_alignRight="@+id/button"
        android:layout_alignEnd="@+id/button"
        android:layout_marginTop="88dp" />
</RelativeLayout>

package com.example.wuxueyou.myfirstandroidapplication;

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.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wuxueyou.Utils.ClientThread;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";
    private Button button;
    private TextView textview;
    private EditText editText;
    private Button buttonSend;
    private Handler handler;
    private ClientThread clientThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) this.findViewById(R.id.button);
        buttonSend = (Button) this.findViewById(R.id.button2);
        textview = (TextView) this.findViewById(R.id.textView2);
        editText = (EditText) this.findViewById(R.id.editText);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("--> this is sysout");
                Log.i(TAG, "==>this is Log out");
                Toast.makeText(MainActivity.this, "this is a Toast", Toast.LENGTH_SHORT).show();
            }
        });
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == 0x999){
                    textview.append(msg.obj.toString().trim() + "\n");
                }
            }
        };
        clientThread = new ClientThread(handler);
        new Thread(clientThread).start();
        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = new Message();
                msg.what = 0x123;
                msg.obj = editText.getText().toString().trim();
                clientThread.SendHandler.sendMessage(msg);
                editText.setText("");
            }
        });

    }
}

package com.example.wuxueyou.Utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by wuxueyou on 16/9/12.
 */
public class ClientThread implements Runnable{
    public Handler SendHandler;
    private OutputStream outputStream = null;
    public  Handler recvHandler;
    private BufferedReader br = null;

    public ClientThread(Handler recvHandler) {
        this.recvHandler = recvHandler;
    }

    public void run(){
        try {
            Socket s = new Socket("192.168.0.109",61000);
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            outputStream = s.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread(){
            @Override
            public void run() {
                String content = null;
                try {
                    while((content = br.readLine())!= null){
                        Message msg = new Message();
                        msg.what = 0x999;
                        msg.obj =content;
                        recvHandler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        Looper.prepare();
        SendHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == 0x123){
                    try {
                        outputStream.write((msg.obj.toString().trim() + "\r\n").getBytes("utf-8"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        Looper.loop();
    }
}

运行结果:

此时服务器端的输出:


值得注意的是,在使用OutputStream的时候,一定要在字符串后面加上“\r\n”,否则发送之后,服务器端接收不到。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值