您的位置:首页 > 理论基础 > 计算机网络

android tcp server

2016-03-04 11:05 429 查看
(1)BYTE TO STRING
(2)STRING TO BYTE
(3)THREAD
(4)HANDLE
 

package com.FJICC.lzm;     

import java.util.ArrayList;   

import java.util.Enumeration;   

import java.io.BufferedReader;   

import java.io.IOException;   

import java.io.InputStream;   

import java.io.InputStreamReader;   

import java.io.OutputStream;   

import java.net.InetAddress;   

import java.net.NetworkInterface;   

import java.net.Socket;   

import java.net.ServerSocket;   

  

import android.app.Activity;   

import android.app.AlertDialog;   

import android.app.Dialog;   

import android.content.Context;   

import android.content.DialogInterface;   

import android.content.Intent;   

import android.os.Bundle;   

import android.os.Handler;   

import android.os.Message;   

import android.view.View;   

import android.widget.Button;   

import android.widget.EditText;   

import android.widget.TextView;   

  

  

public class tcp_server extends Activity{   

       

private Button serverStart_btn;   

private Button serverStop_btn;   

private TextView receivedata_tv;   

private Button setport_btn;   

private EditText senddata_et;   

private Button send_btn;   

public int PORT = 8080;   

public Handler mHandler;   

protected static final int GUINOTIFIER = 0x1234;   

  

@Override  

public void onBackPressed() {   

    // TODO Auto-generated method stub   

    super.onBackPressed();   

    Intent i =new Intent();   

    i.setClass(tcp_server.this,MainActivity.class);   

    startActivity(i);   

    finish();   

}   

@Override  

protected void onCreate(Bundle savedInstanceState) {   

    // TODO Auto-generated method stub   

    super.onCreate(savedInstanceState);   

    setContentView(R.layout.tcpserver_main);   

       

    serverStart_btn=(Button)findViewById(R.id.btnStart);   

    serverStop_btn=(Button)findViewById(R.id.btnStop);   

    setport_btn=(Button)findViewById(R.id.btnSet);   

    send_btn=(Button)findViewById(R.id.btnSend);   

       

    senddata_et=(EditText)findViewById(R.id.et_send);   

    receivedata_tv=(TextView)findViewById(R.id.tv_receive);   

  

    serverStart_btn.setOnClickListener(new Button.OnClickListener(){   

        @Override  

        public void onClick(View v) {   

            // TODO Auto-generated method stub   

            serverStart_btn.setEnabled(false);   

            setport_btn.setEnabled(false);   

            serverStop_btn.setEnabled(true);   

               

            new Thread()   

            {   

                @Override  

                public void run() {   

                    // TODO Auto-generated method stub   

                    super.run();   

                    ServerSocket serverSocket=null;   

                    try{   

                        //创建ServerSocket对象监听PORT端口   

                        serverSocket = new ServerSocket(PORT);   

                        //接收tcp连接返回socket对象   

                        Socket socket= serverSocket.accept();   

                           

                        //获得输入流   

                        InputStream inputStream=socket.getInputStream();   

                        ///////////////////////////////////////////////////////////////////////////////////////   

                        //获得输出流   

                        OutputStream outputStream = socket.getOutputStream();   

                        byte []byteBuffer=new byte[1024];   

                        int temp = 0;   

                        String s;   

                        //读取接收到的数据   

                        while((temp = inputStream.read(byteBuffer))!=-1)   

                            {   

                            outputStream.write(byteBuffer, 0, temp);   

                            //将byte转为string   

                            //String(byte[], int, int)使用平台的缺省字符编码方式转换指定的字节子数组生成一新的 String    

                            s = new String(byteBuffer,0,temp);   

                               

                            //将string转byte   

                            //byte[] bs = str.getBytes();   

                               

                            //定义一个message的变量m   

                            Message m = new Message();   

                            //消息的标记GUINOTIFIER在前面定义的   

                            m.what = tcp_server.GUINOTIFIER;   

                            //将要传送的数据传递给 m.obj   

                            m.obj =s;   

                            //传送消息   

                            tcp_server.this.mHandler.sendMessage(m);   

                            }   

                        //System.out.println(new String(byteBuffer,0,temp));   

                        outputStream.flush();                          

                        socket.close();   

                        serverSocket.close();   

                                                                           

                    }catch(IOException e){   

                        e.printStackTrace();   

                    }   

                }                  

            }.start();   

        }      

    });    

  

    //创建handler   

    mHandler = new Handler() {   

            public void handleMessage(Message msg) {   

                switch (msg.what) {//得到Handle的通知了 这个时候你可以做相应的操作   

                    case tcp_server.GUINOTIFIER://tcp_server是Activity的类名          

                        //清空textView   

                        receivedata_tv.setText("");   

                        //设置textView显示内容   

                        receivedata_tv.setText(msg.obj.toString());   

                        break;   

                }   

                super.handleMessage(msg);   

            }   

        };   

        //结束TCP服务器   

        serverStop_btn.setOnClickListener(new Button.OnClickListener(){   

            @Override  

            public void onClick(View v) {   

                serverStart_btn.setEnabled(true);   

                setport_btn.setEnabled(true);   

                serverStop_btn.setEnabled(false);   

                   

                Intent i =new Intent();   

                i.setClass(tcp_server.this,MainActivity.class);   

                startActivity(i);   

                finish();   

            }});   

}   

  

}   

  

  

tcpserver_main.xml   

<?xml version="1.0" encoding="UTF-8"?>   

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    android:layout_width="fill_parent"  

    android:layout_height="fill_parent"  

    android:orientation="vertical" >   

  

    <LinearLayout   

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_gravity="center_horizontal"  

        android:orientation="horizontal" >   

  

        <Button   

            android:id="@+id/btnStart"  

            style="?android:attr/buttonStyleSmall"  

            android:layout_width="wrap_content"  

            android:layout_height="wrap_content"  

            android:text="开启服务" />   

  

        <Button   

            android:id="@+id/btnStop"  

            style="?android:attr/buttonStyleSmall"  

            android:layout_width="wrap_content"  

            android:layout_height="wrap_content"  

            android:text="关闭服务" />   

  

        <Button   

            android:id="@+id/btnSet"  

            style="?android:attr/buttonStyleSmall"  

            android:layout_width="wrap_content"  

            android:layout_height="wrap_content"  

            android:text="端口设置" />   

    </LinearLayout>   

  

    <TextView   

        android:id="@+id/tv_receive"  

        android:layout_width="match_parent"  

        android:layout_height="wrap_content"  

        android:layout_weight="0.70"  

        android:text="TextView" />   

  

    <EditText   

        android:id="@+id/et_send"  

        android:layout_width="match_parent"  

        android:layout_height="wrap_content"  

        android:ems="10"  

        android:inputType="textMultiLine" >   

  

        <requestFocus />   

    </EditText>   

  

    <Button   

        android:id="@+id/btnSend"  

        style="?android:attr/buttonStyleSmall"  

        android:layout_width="148dp"  

        android:layout_height="wrap_content"  

        android:layout_gravity="center_horizontal"  

        android:text="发送" />   

  

</LinearLayout>   

  

  

  

<uses-permission android:name="android.permission.INTERNET"/> 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: