android-学习-socket.1

来源:互联网 发布:激光雷达识别软件 编辑:程序博客网 时间:2024/04/29 19:45

Androidmanifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.administrator.sockettx">    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>    <uses-permission android:name="android.permission.INTERNET"/>    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".AndroidService"/>    </application></manifest>

MainActivity.xml

<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=".MainActivity" >    <EditText        android:id="@+id/ed1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="给服务器发送信息"/>    <Button        android:id="@+id/send"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/ed1"        android:text="发送"/>    <TextView        android:id="@+id/txt1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true"        android:layout_below="@+id/server_ip" />    <Button        android:text="重置"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/send"        android:layout_centerHorizontal="true"        android:id="@+id/reset" />    <EditText        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:inputType="textPersonName"        android:ems="10"        android:id="@+id/port"        android:hint="port"        android:layout_alignBaseline="@+id/server_ip"        android:layout_alignBottom="@+id/server_ip"        android:layout_alignParentRight="true"        android:layout_alignParentEnd="true"        android:layout_toRightOf="@+id/server_ip"        android:layout_toEndOf="@+id/server_ip" />    <EditText        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:inputType="textPersonName"        android:ems="10"        android:hint="server_ip"        android:id="@+id/server_ip"        android:layout_below="@+id/reset"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true" /></RelativeLayout>

MainActivity:

package com.example.administrator.sockettx;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketTimeoutException;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class MainActivity extends Activity {    Socket socket = null;    String buffer = "";    TextView txt1;    Button send;    EditText ed1;    String geted1;    Button reset;    EditText server_ip;    EditText port;    public Handler myHandler = new Handler() {        @Override        public void handleMessage(Message msg) {            if (msg.what == 0x11) {                Bundle bundle = msg.getData();                txt1.append("server:"+bundle.getString("msg")+"\n");            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        txt1 = (TextView) findViewById(R.id.txt1);        send = (Button) findViewById(R.id.send);        ed1 = (EditText) findViewById(R.id.ed1);        reset = (Button)findViewById(R.id.reset);        server_ip = (EditText)findViewById(R.id.server_ip);        port = (EditText)findViewById(R.id.port);        reset.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                txt1.setText("");                ed1.setText("");            }        });        send.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                geted1 = ed1.getText().toString();                int count = 0;                count++;                if(geted1.equals("")){                    txt1.append("ERRROR!!请输入数据!\n");                    if(count>=5){                        txt1.setText("");                    }                }else {                    //启动线程 向服务器发送和接收信息                    new MyThread(geted1).start();                    txt1.append("client:"+geted1+"\n");                }            }        });    }    class MyThread extends Thread {        public String txt1;        public MyThread(String str) {            txt1 = str;        }        @Override        public void run() {            //定义消息            Message msg = new Message();            msg.what = 0x11;            Bundle bundle = new Bundle();            String sre_ip=server_ip.getText().toString().trim();            String str_port = port.getText().toString().trim();            bundle.clear();            try {                //连接服务器 并设置连接超时为5秒                socket = new Socket();                //socket.connect(new InetSocketAddress("1.1.9.30", ), 5000);                socket.connect(new InetSocketAddress("192.168.0.100", 30000), 5000);                //获取输入输出流                OutputStream ou = socket.getOutputStream();                BufferedReader bff = new BufferedReader(new InputStreamReader(                        socket.getInputStream()));                //读取发来服务器信息                String line = null;                buffer="";                while ((line = bff.readLine()) != null) {                    buffer = line + buffer;                }                //向服务器发送信息                ou.write("android 客户端".getBytes("gbk"));                ou.flush();                bundle.putString("msg", buffer.toString());                msg.setData(bundle);                //发送消息 修改UI线程中的组件                myHandler.sendMessage(msg);                //关闭各种输入输出流                bff.close();                ou.close();                socket.close();            } catch (SocketTimeoutException aa) {                //连接超时 在UI界面显示消息                bundle.putString("msg", "连接超时!服务器连接失败!请检查网络是否打开");                msg.setData(bundle);                //发送消息 修改UI线程中的组件                myHandler.sendMessage(msg);            } catch (IOException e) {                e.printStackTrace();            }        }    }}

AndroidRunable :

package com.example.administrator.sockettx;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.Socket;public class AndroidRunable implements Runnable {    Socket socket = null;    public AndroidRunable(Socket socket) {        this.socket = socket;    }    @Override    public void run() {        // 向android客户端输出hello worild        String line = null;        InputStream input;        OutputStream output;        String str = "hello world!";        try {            //向客户端发送信息            output = socket.getOutputStream();            input = socket.getInputStream();            BufferedReader bff = new BufferedReader(                    new InputStreamReader(input));            output.write(str.getBytes("gbk"));            output.flush();            //半关闭socket            socket.shutdownOutput();            //获取客户端的信息            while ((line = bff.readLine()) != null) {                System.out.print(line);            }            //关闭输入输出流            output.close();            bff.close();            input.close();            socket.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

AndroidService

package com.example.administrator.sockettx;import android.app.Activity;import android.os.Bundle;import android.support.annotation.Nullable;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList;import java.util.List;public class AndroidService extends Activity{public void onCreate(Bundle save){    super.onCreate(save);    setContentView(R.layout.activity_main);    ServerSocket serivce = null;    try {        serivce = new ServerSocket(30000);        while (true) {            //等待客户端连接            Socket socket = serivce.accept();            new Thread(new AndroidRunable(socket)).start();        }    } catch (IOException e) {        e.printStackTrace();    }}}
0 0