wifi,tcp通信数据发送接收客户端服务器安卓源码

来源:互联网 发布:to淘宝图片空间 编辑:程序博客网 时间:2024/04/29 05:26

//主活动

MainActivity.java文件:

package com.example.xx.yyyy;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.os.StrictMode;import android.text.method.ScrollingMovementMethod;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ScrollView;import android.widget.TextView;import android.widget.Toast;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;public class MainActivity extends Activity {    EditText  IPText,PORTText, editMsgText;    Button  sendButtonServer, startButton;    TextView recvText;    ScrollView textScrollView;    private Context mContext;    private boolean isConnecting = false;    private Thread mThreadClient = null;    private Thread mThreadServer = null;    private Socket mSocketServer = null;    private Socket mSocketClient = null;    static BufferedReader mBufferedReaderServer    = null;    static PrintWriter mPrintWriterServer = null;    static BufferedReader mBufferedReaderClient    = null;    static PrintWriter mPrintWriterClient = null;    private  String recvMessageClient = "";    private  String recvMessageServer = "";    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);//加载onCreate函数        setContentView(R.layout.activity_main);//<span style="" font-size:9.0pt;"="">载入界面activity_main        mContext = this;        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()                .detectDiskReads()                .detectDiskWrites()                .detectNetwork()   // or .detectAll() for all detectable problems                .penaltyLog()                .build());        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()                .detectLeakedSqlLiteObjects()                .penaltyLog()                .penaltyDeath()                .build());        IPText = (EditText) findViewById(R.id.IPText);        PORTText = (EditText) findViewById(R.id.port);        editMsgText = (EditText) findViewById(R.id.MessageText);        sendButtonServer = (Button) findViewById(R.id.SendButtonServer);        startButton = (Button) findViewById(R.id.CreateConnect);        recvText = (TextView) findViewById(R.id.RecvText);        recvText.setMovementMethod(ScrollingMovementMethod.getInstance());        textScrollView = (ScrollView) findViewById(R.id.scrollView);        startButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (isConnecting)                {                    isConnecting = false;                    try {                        if(mSocketClient!=null)                        {                            mSocketClient.close();                            mSocketClient = null;                            mPrintWriterClient.close();                            mPrintWriterClient = null;                        }                    } catch (IOException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    mThreadClient.interrupt();                    startButton.setText("开始连接");                    IPText.setEnabled(true);                    PORTText.setEnabled(true);                    //recvText.setText("信息:\n");                }                else                {                    isConnecting = true;                    startButton.setText("停止连接");                    IPText.setEnabled(false);                    PORTText.setEnabled(false);                    mThreadClient = new Thread(mRunnable);                    mThreadClient.start();                }            }        });        sendButtonServer.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                if (isConnecting && mSocketClient!=null)                {                    String msgText =editMsgText.getText().toString();//取得编辑框中我们输入的内容                    if(msgText.length()<=0)                    {                        Toast.makeText(mContext, "<span style="" font-size:"="">发送内容不能为空!", Toast.LENGTH_SHORT).show();                    }                    else                    {                        try                        {                            mPrintWriterClient.print(msgText);//发送给服务器                            mPrintWriterClient.flush();                        }                        catch (Exception e)                        {                            // TODO: handle exception                            Toast.makeText(mContext, "<span style="" font-size:"="">发送异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();                        }                    }                }                else                {                    Toast.makeText(mContext, "<span style="" font-size:"="">没有连接", Toast.LENGTH_SHORT).show();                }            }        });    }        //<span style="" font-size:9.0pt;"="">线程:监听服务器发来的消息        private Runnable   mRunnable  = new Runnable()        {            public void run()            {                String msgText =IPText.getText().toString();                if(msgText.length()<=0)                {                    //Toast.makeText(mContext, "IP不能为空!", Toast.LENGTH_SHORT).show();                    recvMessageClient = "IP不能为空!\n";//<span style="" font-size:9.0pt;"="">消息换行                    Message msg = new Message();                    msg.what = 1;                    mHandler.sendMessage(msg);                    return;                }                String sIP = msgText;                String sPort = PORTText.getText().toString();                int port = Integer.parseInt(sPort);                Log.d("gjz", "IP:" + sIP + ":" + port);                try                {                    //连接服务器                    mSocketClient = new Socket(sIP, port); //portnum                    //取得输入、输出流                    mBufferedReaderClient = new BufferedReader(new InputStreamReader(mSocketClient.getInputStream()));                    mPrintWriterClient = new PrintWriter(mSocketClient.getOutputStream(), true);                    recvMessageClient = "<span style="" font-size:"="">已经连接server!\n";//<span style="" font-size:9.0pt;"="">消息换行                    Message msg = new Message();                    msg.what = 1;                    mHandler.sendMessage(msg);                    //break;                }                catch (Exception e)                {                    recvMessageClient = "<span style="" font-size:"="">连接IP异常:" + e.toString() + e.getMessage() + "\n";//256];                int count = 0;                while (isConnecting)                {                    try                    {                        //if ( (recvMessageClient = mBufferedReaderClient.readLine()) != null )                        if((count = mBufferedReaderClient.read(buffer))>0)                        {                            recvMessageClient = getInfoBuff(buffer, count) + "\n";//<span style="" font-size:9.0pt;"="">消息换行                            Message msg = new Message();                            msg.what = 1;                            mHandler.sendMessage(msg);                        }                    }                    catch (Exception e)                    {                        recvMessageClient = "<span style="" font-size:"="">接收异常:" + e.getMessage() + "\n";//刷新                            textScrollView.post(new Runnable() {                                public void run() {                                    textScrollView.fullScroll(ScrollView.FOCUS_DOWN);                                }                            });                        }                    });                }            }        };        //0; i<count; i++)            {                temp[i] = buff[i];            }            return new String(temp);        }        public void onDestroy() {            super.onDestroy();            if (isConnecting)            {                isConnecting = false;                try {                    if(mSocketClient!=null)                    {                        mSocketClient.close();                        mSocketClient = null;                        mPrintWriterClient.close();                        mPrintWriterClient = null;                    }                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                mThreadClient.interrupt();            }            if (serverRuning)            {                serverRuning = false;                try {                    if(serverSocket!=null)                    {                        serverSocket.close();                        serverSocket = null;                    }                    if(mSocketServer!=null)                    {                        mSocketServer.close();                        mSocketServer = null;                    }                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                mThreadServer.interrupt();            }        }}

 

 

<AbsoluteLayout    android:layout_width="wrap_content"    android:layout_height="wrap_content"    xmlns:android="http://schemas.android.com/apk/res/android"    >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textAppearance="?android:attr/textAppearanceLarge"        android:text="服务器ip地址"        android:id="@+id/textView"        android:layout_x="3dp"        android:layout_y="11dp" />    <EditText        android:layout_width="254dp"        android:layout_height="wrap_content"        android:id="@+id/IPText"        android:layout_x="131dp"        android:layout_y="3dp" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textAppearance="?android:attr/textAppearanceLarge"        android:text="端口值"        android:id="@+id/textView2"        android:layout_x="4dp"        android:layout_y="38dp" />    <EditText        android:layout_width="296dp"        android:layout_height="wrap_content"        android:id="@+id/port"        android:layout_x="74dp"        android:layout_y="32dp" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="连接"        android:id="@+id/CreateConnect"        android:layout_x="27dp"        android:layout_y="69dp" />    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textAppearance="?android:attr/textAppearanceLarge"        android:text="收到的信息是:"        android:id="@+id/textView3"        android:layout_x="5dp"        android:layout_y="132dp" />    <ScrollView        android:layout_width="359dp"        android:layout_height="277dp"        android:id="@+id/scrollView"        android:layout_x="6dp"        android:layout_y="159dp" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textAppearance="?android:attr/textAppearanceLarge"            android:text="Large Text"            android:id="@+id/RecvText" />    </ScrollView>    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="发送"        android:id="@+id/SendButtonServer"        android:layout_x="313dp"        android:layout_y="455dp" />    <EditText        android:layout_width="306dp"        android:layout_height="wrap_content"        android:id="@+id/MessageText"        android:layout_x="6dp"        android:layout_y="465dp" /></AbsoluteLayout>

 

 

 

 

 

 

 

 

 

 

 

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.lu.wifi" >    <uses-permission android:name="android.permission.WRITE_SETTINGS" />    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.READ_PHONE_STATE" />    <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"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

 


0 0
原创粉丝点击