Android网络编程之四:Socket编程

来源:互联网 发布:乖离数据下载很慢 编辑:程序博客网 时间:2024/05/19 22:48

先讲点硬件配置吧,否则这个非常难测试。用模拟器调试会让人崩溃,太久了,而且往往会让人非常难受。我习惯用手机来测试程序:

硬件条件:

1、PC,肯定得有了

2、无线路由(50块左右,只要能用就行)

3、手机

谈点个人看法:Java Socket编程还是跟C#还是有点点区别,Java表现形式要比C#稍多,但万变不离其中。以下是大家用的形式,

费话少说,下面介绍原码:

1、服务器端程序:

public class testserver {

    public static void main(String[] args) {
        try
        {
            ServerSocket server=new ServerSocket(8888);
            Socket client;
            DataInputStream in;
            DataOutputStream out;
            byte[] buffers=new byte[1024];
            while(true)
            {
                try
                {
                    client=server.accept();
                    in=new DataInputStream(client.getInputStream());
                    out=new DataOutputStream(client.getOutputStream());
                    String msg=in.readUTF();
                    System.out.println("客户端:"+msg);
                    out.writeUTF("已经收到!");
                }
                catch(Exception ex)
                {
                    System.out.println(ex.toString());
                }
            }
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
        }
    }

}

2、布局文件

<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"
    tools:context="com.example.testclient.MainActivity" >

    <EditText
        android:id="@+id/etMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="108dp"
        android:ems="10"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="false"
        android:layout_below="@id/etMsg" >

        <EditText
            android:id="@+id/etSendMsg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10" />

        <Button
            android:id="@+id/btnSend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="发送" />

    </LinearLayout>

</RelativeLayout>

3、程序原代码(前面多线程的程序用上了哟)

public class MainActivity extends Activity implements OnClickListener {
    private Socket client;
    private EditText etMsg,etSendMsg;
    private Button btnSend;
    private String strMsg;
    private Handler mHandler=new Handler(){
        public void handleMessage(Message msg) {
            etMsg.append(strMsg);
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
        super.onCreate(savedInstanceState);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());

        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());


        setContentView(R.layout.main);
        etMsg=(EditText)findViewById(R.id.etMsg);
        etSendMsg=(EditText)findViewById(R.id.etSendMsg);
        btnSend=(Button)findViewById(R.id.btnSend);
        btnSend.setOnClickListener(this);
        connectServer();
    }
    private void connectServer()
    {
        
        String ip="172.168.11.15";
        try {
            client=new Socket(ip,8888);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            client=null;
        }
        
        new Thread(new Runnable(){

            @Override
            public void run() {
                DataInputStream in;
                
                while(true)
                {
                    try {
                        in=new DataInputStream(client.getInputStream());
                        
                        strMsg=in.readUTF().toString();
                        Log.i("Test", strMsg);
                        mHandler.sendMessage(mHandler.obtainMessage());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                }
            }
            
        }).start();;
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        try
        {
            DataOutputStream out=new DataOutputStream(client.getOutputStream());
            out.writeUTF(etSendMsg.getText().toString());
        }
        catch(Exception e)
        {}
    }

    
}


附上键盘输入全部字符串:
1 2 3 4 5 6 7 8 9 0

a b c d e f g h i j k l m n o p q r s t u v w x y z

! @ # $ % ^ & * ( ) _ + |  { } : "  <  > ?


0 0