Android Socket 编程尝试

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.cmono.asynctasktest.MainActivity"
    tools:ignore="MergeRootFrame" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        <EditText
            android:id="@+id/editText1"
            android:hint="服务器地址或服务器名称"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10" >
            <requestFocus />
        </EditText>
        <EditText
            android:id="@+id/editText2"
            android:hint="端口号"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />
                            
        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="ConnectServer"
            android:text="连接服务器" />
                            
         <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:onClick="DisconnectServer"
            android:text="断开连接" />
                             
         <EditText
            android:id="@+id/editText3"
            android:hint="输入要发送的文本"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textMultiLine"
            android:ems="10" >
            <requestFocus />
        </EditText>
                            
        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="SendMessage"
            android:enabled="false"
            android:text="发送到服务端" />
                            
        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="ScanCode"
            android:text="扫描码" />
        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="操作提示\n"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>
</FrameLayout>

package net.cmono.asynctasktest;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
    Socket socket;
    EditText et1;
    EditText et2;
    EditText et3;
    TextView tv;
    Button btnConnent;
    Button btnDisconnect;
    Button btnSendMessage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        et1 = (EditText) this.findViewById(R.id.editText1);
        et2 = (EditText) this.findViewById(R.id.editText2);
        et3 = (EditText) this.findViewById(R.id.editText3);
        tv = (TextView)this.findViewById(R.id.textView1);
        btnConnent = (Button)this.findViewById(R.id.button1);
        btnDisconnect = (Button)this.findViewById(R.id.button2);
        btnSendMessage = (Button)this.findViewById(R.id.button3);
    }
    public void ScanCode(View v){
                    
    }
                
    public void ConnectServer(View v) {
        if (et1 != null && et2 != null && et1.getText().toString().length() > 0
                && et2.getText().toString().length() > 0) {
            ConnentTask cTask = new ConnentTask();
            ServerAddress sa = new ServerAddress();
            sa.Address = et1.getText().toString();
            sa.Port = Integer.parseInt(et2.getText().toString());
            sa.Data = "黄河黄河,我是长江";
                        
            cTask.execute(sa);
        } else {
            ShowDialog("必须输入");
        }
    }
                
    public void SendMessage(View v) throws IOException {
        if (socket!=null && socket.isConnected()){
                        
            new Thread() { 
                   //点击button后,会开一个新的线程! 
                @Override 
                public void run() { 
                    //重写线程中的run方法 
                 try { 
                              
                        BufferedWriter writer = new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream()));
                        writer.write(et3.getText().toString());
                        writer.flush();
                            
                  //关闭流 
                  //抛出异常是必须的! 
                 } catch (UnknownHostException e) { 
                  // TODO Auto-generated catch block 
                  e.printStackTrace(); 
                 } catch (IOException e) { 
                  // TODO Auto-generated catch block 
                  e.printStackTrace(); 
                 } 
                             
                } 
               }.start(); 
                        
            ShowDialog("发送成功");
        } else {
            ShowDialog("发送失败");
        }
    }
                
    public void DisconnectServer(View v) throws IOException {
        if (socket!=null && socket.isConnected()){
                        
            new Thread() { 
                   //点击button后,会开一个新的线程! 
                @Override 
                public void run() { 
                    //重写线程中的run方法 
                 try { 
                              
                        BufferedWriter writer = new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream()));
                        writer.write("Close");
                        writer.flush();
                            
                  //关闭流 
                  //抛出异常是必须的! 
                 } catch (UnknownHostException e) { 
                  // TODO Auto-generated catch block 
                  e.printStackTrace(); 
                 } catch (IOException e) { 
                  // TODO Auto-generated catch block 
                  e.printStackTrace(); 
                 } 
                             
                } 
               }.start(); 
                        
            ShowDialog("成功断开连接");
            btnConnent.setEnabled(true);
            btnDisconnect.setEnabled(false);
            btnSendMessage.setEnabled(false);
        } else {
            ShowDialog("尚未连接");
        }
    }
    class ServerAddress {
        public String Address;
        public int Port;
        public String Data;
    }
    class ConnentTask extends AsyncTask<ServerAddress, Object, String> {
                    
        // 表示任务执行之前的操作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            btnConnent.setEnabled(false);
                        
            tv.append((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()).toString() + "\n开始提交了哦\n");
        }
                    
        // 完成更新UI操作
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            tv.append((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()).toString() + "\n好快啊,执行完了\n");
            tv.append("返回结果: " + result);
            ShowDialog(result);
            btnDisconnect.setEnabled(true);
            btnSendMessage.setEnabled(true);
        }
                    
        @Override
        protected void onProgressUpdate(Object... values) {
            super.onProgressUpdate(values);
            tv.append((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()).toString() + "\n");
        }
                    
        @Override
        protected String doInBackground(ServerAddress... params) {
            // TODO Auto-generated method stub
            ServerAddress sa = params[0];
                        
            String recvMsg = "";
                        
            try {
                socket = new Socket(sa.Address, sa.Port);
                String socketData = sa.Data;
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream()));
                writer.write(socketData.replace("\n", " ") + "\n");
                writer.flush();
                            
                /*** Socket客户端读取服务器端响应数据   ****/ 
                //socket.isConnected代表是否连接成功过 
                if((socket.isConnected() == true) && (socket.isClosed() == false)){//判断Socket是否处于连接状态 
                    //客户端接收服务器端的响应,读取服务器端向客户端的输入流 
                    InputStream is = socket.getInputStream(); 
                    //缓冲区 
                    byte[] buffer = new byte[is.available()]; 
                    //读取缓冲区 
                    is.read(buffer); 
                    //转换为字符串 
                    recvMsg = new String(buffer); 
                }   
                           
                //关闭网络 
//              socket.close();
                            
//              BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
//              String recvMsg = reader.readLine();
//             
//              writer.close();
//              reader.close();
//              socket.close();
                            
                return recvMsg;
                //return "服务器给结果了,但是我觉得告诉你一句 Hello World 比较好!";
                            
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                        
                        
            return "发生已知异常,但是我就不告诉你";
        }
    }
    void ShowDialog(String msg) {
        new AlertDialog.Builder(MainActivity.this)
                .setIcon(R.drawable.ic_launcher).setTitle("提示信息")
                .setMessage(msg)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        /* User clicked OK so do some stuff */
                    }
                }).setNegativeButton("取消", null).create().show();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        public PlaceholderFragment() {
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }
}

点击查看原图点击查看原图点击查看原图

知识共享许可协议
《Android Socket 编程尝试》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     165.58ms