Android客户端通过socket与服务器通信

下面是一个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

你可能感兴趣的:(Android学习)