关闭

安卓APP客户端与服务器通信

标签: android通信服务器app
1644人阅读 评论(0) 收藏 举报

安卓4.0以后副线程无法直接访问UI组件,所以需创建一个Handler对象用于传递主线程与副线程之间的数据下面是代码演示:

服务器:

package socketTest;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class socketTest {
public static void main(String[] args) throws UnknownHostException, IOException {
ServerSocket myServerSocket=new ServerSocket(4368);
System.out.println("正在连接服务器");

//此线程用于服务器接收消息
new Thread(){
public void run()
{
ServerSocket myServerSocketRead=null;
try {
myServerSocketRead=new ServerSocket(4369);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("正在连接传输服务器");

while(true)
{
Socket mysocketRead=null;
try {
mysocketRead=myServerSocketRead.accept();
System.out.println("传输服务器连接成功!");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DataInputStream myreader=null;
try {
myreader = new DataInputStream(mysocketRead.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

String b=null;
try {
b = myreader.readUTF();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(b);

}
}
}.start();
while(true)
{

Socket mySocket=myServerSocket.accept();
System.out.println("连接成功!");


DataOutputStream mywriter=new DataOutputStream(mySocket.getOutputStream());

String a=new Scanner(System.in).nextLine();
mywriter.writeUTF(a);




}


}
}


客户端主要代码:

package com.example.user.sockettest;

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 java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import android.os.Handler;
import java.util.logging.LogRecord;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private Handler handler;
    private Button send;
    private EditText editText;
    private myThead mythead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView= (TextView) findViewById(R.id.text);//用于接收消息
        send= (Button) findViewById(R.id.send);//用于发送消息
        editText= (EditText) findViewById(R.id.edittext);//用于发送消息

        handler=new Handler()
        {
            @Override
            public void handleMessage(Message msg) {
               if(msg.what==0x123)
               {
                   Log.e("bbb",(String)msg.obj);
                   textView.setText((String)msg.obj);
               }
            }
        };

      mythead=new myThead(handler);
        mythead.start();
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new MyWrite(editText.getText().toString()).start();
                Log.e("即将进入传输线程","1");
            }

        });


    }
}
package com.example.user.sockettest;

import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.os.Handler;

/**
 * Created by user on 2016/8/24.
 */
public class myThead extends Thread {
    private Handler handler;
    public Handler revhandler;
    private DataInputStream myreader=null;
    private DataOutputStream mywriter=null;
    private Socket socket=null;

    public myThead(Handler handler)
    {
        this.handler=handler;
    }
    @Override
    public void run() {

        while (true) {


            try {
                socket = new Socket("172.20.0.158", 4368);
            } catch (IOException e) {
                e.printStackTrace();
            }


            try {
                myreader = new DataInputStream(socket.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }


            Log.e("juge", "run: aaaaaa");
            String flag = null;

            try {
                flag = myreader.readUTF();
                Message message = new Message();
                message.what = 0x123;
                message.obj = flag;
                handler.sendMessage(message);
                Log.e("aaa", "run: " + flag);
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}
package com.example.user.sockettest;

import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * Created by user on 2016/8/28.
 */
public class MyWrite extends Thread {
    private String write;

    public MyWrite(String write)
    {
        this.write=write;
    }
    @Override
    public void run() {
        Socket socket=null;
        Log.e("进入传输线程","111");
        try {
            socket = new Socket("172.20.0.158", 4369);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("进入传输线程","222");
        DataOutputStream mywriter=null;
        try {
            mywriter = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("进入传输线程","3");
        try {
            mywriter.writeUTF(write);
            Log.e("书写成功!","");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e("进入传输线程","4");

    }
}

0
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1936次
    • 积分:69
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类