下面是一个demo,Android客户端通过socket与服务器通信。

由于Android里面可以完全使用java.io.*包和java.net.*包,那么,实际上,逻辑部分与J2SE没有区别。只是UI代码不一样。

Android客户端通过socket与服务器通信分为下面5步:

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

socket = new Socket("10.14.114.127",54321); //IP:10.14.114.127,端口54321

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

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

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

(3)对Socket进行读写

out.println(message);

(4)关闭打开的流

out.close();

完整工程代码如下:

package com.yarin.android.Examples_08_04; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Activity01 extends Activity { private final String DEBUG_TAG = "Activity01"; private TextView mTextView = null; private EditText mEditText = null; private Button mButton = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mButton = (Button)findViewById(R.id.Button01); mTextView = (TextView)findViewById(R.id.TextView01); mEditText = (EditText)findViewById(R.id.EditText01); //登陆 mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Socket socket = null; String message = mEditText.getText().toString() + "/r/n"; try { //创建Socket // socket = new Socket("192.168.1.110",54321); socket = new Socket("10.14.114.127",54321); //IP:10.14.114.127,端口54321 //向服务器发送消息 PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); out.println(message); //接收来自服务器的消息 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg = br.readLine(); if ( msg != null ) { mTextView.setText(msg); } else { mTextView.setText("数据错误!"); } //关闭流 out.close(); br.close(); //关闭Socket socket.close(); } catch (Exception e) { // TODO: handle exception Log.e(DEBUG_TAG, e.toString()); } } }); } }

布局文件main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="这里显示接收到服务器发来的信息" /> <EditText android:id="@+id/EditText01" android:text="输入要发送的内容" android:layout_width="fill_parent" android:layout_height="wrap_content"> </EditText> <Button android:id="@+id/Button01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="发送" /> </LinearLayout>

AndroidManifest.xml文件如下

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yarin.android.Examples_08_04" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Activity01" 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> <uses-sdk android:minSdkVersion="5" /> </manifest>

当然,还有服务器端得代码

package com.yarin.android.Examples_08_04; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server implements Runnable { public void run() { try { //创建ServerSocket ServerSocket serverSocket = new ServerSocket(54321); while (true) { //接受客户端请求 Socket client = serverSocket.accept(); System.out.println("accept"); try { //接收客户端消息 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String str = in.readLine(); System.out.println("read:" + str); //向服务器发送消息 PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true); out.println("server message"); //关闭流 out.close(); in.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { //关闭 client.close(); System.out.println("close"); } } } catch (Exception e) { System.out.println(e.getMessage()); } } //main函数,开启服务器 public static void main(String a[]) { Thread desktopServerThread = new Thread(new Server()); desktopServerThread.start(); } }

先开启服务器代码,

java Server即可

然后启动android模拟器。运行结果

这是Android客户端。输入12345,点击发送:

Android客户端通过socket与服务器通信_第1张图片

这是服务器端收到的消息

Android客户端通过socket与服务器通信_第2张图片

更多相关文章

  1. androdi与服务器Socket通信原理
  2. 面向UDP的Android——PC双向通信(一):实现Android客户端和PC服务器
  3. Android:SNS客户端开发三:数据库操作(一)
  4. Android与服务器端数据交互(1)
  5. Android 服务器推送技术
  6. 服务器搭建快速入门——适用于Android应用服务器、微信小程序服
  7. 判断客户端类型
  8. android binder c++层 - 回调客户端服务 - 客户端(c++层) 调用

随机推荐

  1. 中国Android应用商店汇总
  2. Android自动提示--AutoCompleteTextView
  3. android工厂类
  4. Android组件界面设计工具 DroidDraw
  5. android开发之res下的menu (xml+代码的形
  6. 自定义圆角button上下间距问题
  7. 单独编译使用WebRTC的音频处理模块 - and
  8. android 面试题一
  9. 《Android(安卓)安全(二)》Smali语法基础
  10. Toast.LENGTH_LONG和Toast.LENGTH_SHORT