Android Socket 基础 & 实例

 

Android客户端通过socket与服务器进行通信可以分为以下几步:

Socket 通信是跨平台的通信,任何平台下,任何语言下,只要基于TCP/IP编写socket通信,都能互相通信。

在服务器端我用的C写的代码。绑定IP,然后监听PORT,等待client的接入。

 

Client应用程序与服务器通信可以采用两种模式:TCP可靠通信 和UDP不可靠通信。

(1)通过IP地址和端口实例化Socket,请求连接服务器:

     socket = new Socket(HOST, PORT);   //host:为服务器的IP地址  port:为服务器的端口号

(2)获取Socket流以进行读写,并把流包装进BufferWriter或者PrintWriter:

   发送字符:把字符数组中的字符串写进Socket

   首先申明,新建对象

   PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);  

   这里涉及了三个类:socket.getOutputStream得到socket的输出字节流,OutputStreamWriter是字节流向字符流转换的桥梁,BufferWriter是字符流,然后再包装进PrintWriter。

   然后对Socket进行写

     if (socket.isConnected()) {
                    if (!socket.isOutputShutdown()) {
                        out.println(msg);
                    }
                }

     msg中的内容为发送内容

 

    接受字符:从Socket中读取字符串

   BufferedReader in = new BufferedReader ( new InputStreamReader(socket.getInputStream()));

   然后对Socket进行读

    if (socket.isConnected()) {
                    if (!socket.isOutputShutdown()) {
                       msg = In.readLine();                    }
                }

      msg为保持接受内容的接收数组

    (3)关闭打开的流

      out.close();

      in.close();

 

 

下面是一个接受一个字符串的例子

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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Connect" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>


下面是接受端代码

package tang.project.socket_test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Socket_testActivity extends Activity {

	TextView tv_msg = null;
	Button btn_send = null;
	static final String HOST = "163.180.117.229";
	static final int PORT = 6000;
	Socket socket = null;
	BufferedReader in = null;
	String content = "";
	Thread Data_Rec;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		tv_msg = (TextView) findViewById(R.id.textView1);
		btn_send = (Button) findViewById(R.id.button1);

		btn_send.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				try {
					socket = new Socket(HOST, PORT);
					in = new BufferedReader(new InputStreamReader(socket
							.getInputStream()));
				} catch (IOException ex) {
					ex.printStackTrace();
					// ShowDialog("login exception" + ex.getMessage());
				}

				Data_Rec = new Thread(new Runnable() {
					public void run() {
						try {
							Rec();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				Data_Rec.start();
			}
		});
		
	}

	public void Rec() throws Exception {

		try {
			if (socket.isConnected()) {
				if (!socket.isInputShutdown()) {
					if ((content = in.readLine()) != null) {
						content += "\n";
						mHandler.sendMessage(mHandler.obtainMessage());
					} else {

					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			tv_msg.setText(tv_msg.getText().toString() + content);
		}
	};

}


 

注意在AndroidManifest.xml中加入对网络的访问权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Manifest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tang.project.socket_test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".Socket_testActivity"
            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>
    
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值