activity_main.java
<LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入要发送的内容"/><Button android:id="@+id/button01" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="连接"/> <Button android:id="@+id/button02" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发送"/> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="vertical" android:fadingEdge="vertical"> <TextViewandroid:id="@+id/textView"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="输出信息:"/> </ScrollView></LinearLayout>界面很是简单。
package com.ryan.socketdemo01;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import java.io.IOException;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.Socket;/** * 本实例功能: 客户端发送数据至客户端(动态输出数据) * */public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button button01 = null; private Button button02 = null; private EditText editText = null; private TextView textView = null; private static Socket ClientSocket = null; private byte[] msgBuffer = null; Handler handler = new Handler(); private void initView() { button01 = (Button) findViewById(R.id.button01); button02 = (Button) findViewById(R.id.button02); editText = (EditText) findViewById(R.id.editText); textView = (TextView) findViewById(R.id.textView); button01.setOnClickListener(this); button02.setOnClickListener(this); button01.setEnabled(true); button02.setEnabled(false); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } @Override public void onClick(View v) { switch (v.getId()){case R.id.button01:// TODO: 15-9-4 socket连接线程connectThread();break;case R.id.button02:// TODO: 15-9-4 发送数据线程sendMsgThread();break; } } private void sendMsgThread() { final String text = editText.getText().toString(); try {msgBuffer = text.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) {e.printStackTrace(); } new Thread(new Runnable() {@Overridepublic void run() {try { OutputStream outputStream; //Socket输出流 outputStream = ClientSocket.getOutputStream(); outputStream.write(msgBuffer); outputStream.flush(); outputStream.close();} catch (IOException e) { e.printStackTrace();}handler.post(new Runnable() { @Override public void run() { textView.append("发送成功:"+text+"
"); }});} }).start(); } private void connectThread() { new Thread(new Runnable() {@Overridepublic void run() {try { ClientSocket = new Socket("10.0.2.2",9001); if (ClientSocket.isConnected()){ handler.post(new Runnable() {@Overridepublic void run() {textView.append("连接成功!"+"
");button01.setEnabled(false);button02.setEnabled(true);} }); }else { handler.post(new Runnable() {@Overridepublic void run() {textView.append("连接失败!"+"
");} }); }} catch (IOException e) { e.printStackTrace();}} }).start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) {return true; } return super.onOptionsItemSelected(item); }}这里我的线程使用方式是:new Thread (new Runnable) { @Override public void run() { } } 网上有人说这个方式很LOW,而且不好,但现在我只会这个,就连asynctask也还在学习中。 Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { textView.append("发送成功:"+text+"
"); }}); 关于几种子线程更新主UI的方法,我以后会再写一篇博客。我现在已经知道了不下4中方法,还没实地操作。 
最初,我对InputStream和OutputStream的方法不是很明了,经常错将InputStream用上write()的方法。 不知在哪里看到这么一段话,I/O流的操作实质是相对于Socket,ServerSocket连接后产生的数据流管道,reader与write是读取与写入的意思,是相对于那个数据流管道进行操作的。即读取管道里的信息,写入信息至管道。不知道这样大家动不动。
最后就是我们要学习的Socket。
他的使用也很简单,建立一个Socket对象,设置IP和端口,获取其I/O流。
ClientSocket = new Socket("10.0.2.2",9001);outputStream = ClientSocket.getOutputStream();到这里基本的使用方法就这么多。
/** * 本实例功能:接受服务器发来的数据 */public class Main {public static void main(String[] args) {// TODO Auto-generated method stubnew SerVerListener().start();}} import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.ServerSocket;import java.net.Socket;import javax.swing.JOptionPane;public class SerVerListener extends Thread{private Socket clientSocket = null;private ServerSocket serverSocket = null;private InputStream inputStream = null;private byte[] buffer = null;@Overridepublic void run() {// TODO Auto-generated method stubtry {serverSocket = new ServerSocket(9001);System.out.println("端口已开启,等待连接中〜〜");//blockclientSocket = serverSocket.accept();System.out.println("已有用户连接");inputStream = clientSocket.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));String str;while((str = br.readLine())!= null){System.out.println(str);}}catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {inputStream.close();serverSocket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}这是服务器端就收到的数据: 
OK,基本就这样。
以上就是本文的全部内容,希望对大家的学习有所帮助。