socket android
参考
http://www.cnblogs.com/dyllove98/p/3149581.html
http://www.cnblogs.com/skyseraph/archive/2012/03/12/2391601.html
一、socket传输模式
两种:TCP, UDP
二、android与服务器通信主要的两种方式
一种是http ,一种是socket.
两者不同:
http使用的“请求-响应”方式。也就是请求时建立 连接通道,当客户端向服务器发送请求后,服务器才返回数据。
socket则是在双方建立起直接进行数据传输,在连接时可以实现数据的主动推送,而不用每资助由客户端发送请求。
三、服务器代码
package chuiyuan.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TcpServer{ // private static final int SERVER_PORT=8888; private static List<Socket> mClientSockets = new ArrayList<Socket>(); //线程池 private ExecutorService mExecutorService ; private ServerSocket mServerSocket ; //start server public static void main (String [] args ){ new TcpServer() ; } //constructor public TcpServer(){ try { mServerSocket = new ServerSocket(SERVER_PORT); //创建 一个线程池 mExecutorService = Executors.newCachedThreadPool() ; System.out.println("start..."); Socket client = null; while (true) { client = mServerSocket.accept() ; mClientSockets.add(client) ; //开一个客户端线程 mExecutorService.execute(new ThreadServer(client)) ; } } catch (IOException e) { e.printStackTrace() ; } } //每个客户端单独开启一个线程 static class ThreadServer implements Runnable{ private Socket mSocket ; private BufferedReader mBufferedReader ; private PrintWriter mPrintWriter ; private String mStrMsg ; public ThreadServer (Socket socket) throws IOException{ mSocket = socket ; mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); mStrMsg = "user:"+this.mSocket.getInetAddress()+" come total:"+mClientSockets.size() ; sendMsg (); } //发送消息给所有客户端 private void sendMsg() throws IOException{ System.out.println(mStrMsg) ; for (Socket client: mClientSockets){ mPrintWriter = new PrintWriter(client.getOutputStream(), true) ; mPrintWriter.println(mStrMsg) ; } } public void run() { try { while ((mStrMsg = mBufferedReader.readLine())!= null) { if (mStrMsg.trim().equals("exit")){ //退出 mClientSockets.remove(mSocket) ; //O(logN) mBufferedReader.close() ; mPrintWriter.close() ; //output stream mStrMsg= "user:"+this.mSocket.getInetAddress()+"exit total:"+ mClientSockets.size() ; mSocket.close() ; sendMsg() ; break ; }else { mStrMsg = mSocket.getInetAddress()+":"+ mStrMsg; sendMsg() ; } } } catch (Exception e) { e.printStackTrace() ; } } } }
安卓客户端
package com.example.tcptest; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import android.support.v7.app.ActionBarActivity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends ActionBarActivity { private Button mInBtn , mSendBtn ; private EditText mEditText1, mEditText2; private static final String SERVERIP ="59.66.116.249" ; private static final int SERVERPORT=8888; private Thread mThread ; private Socket mSocket ; private BufferedReader mBufferedReader ; private PrintWriter mPrintWriter ; private String mStrMsg =""; private static String TAG =MainActivity.class.getSimpleName() ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mInBtn = (Button)findViewById(R.id.myinternet_tcpclient_BtnIn) ; mSendBtn = (Button)findViewById(R.id.myinternet_tcpclient_BtnSend); mEditText1 = (EditText)findViewById(R.id.myinternet_tcpclient_EditText01); mEditText2 = (EditText)findViewById(R.id.myinternet_tcpclient_EditText02); mThread = new Thread(mRunnable) ; //登陆 mInBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { //实例化socket,连接服务器 mSocket = new Socket(SERVERIP, SERVERPORT); //得到socket输入输出流 mBufferedReader = new BufferedReader( new InputStreamReader(mSocket.getInputStream())) ; mPrintWriter = new PrintWriter(mSocket.getOutputStream()) ; mThread.start(); } catch (Exception e) { Log.i(TAG, "socket connect exception:"+ e.getMessage()); e.printStackTrace(); } } }) ; mSendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { String str = mEditText2.getText().toString().trim(); //发送给服务器 mPrintWriter.print(str) ; mPrintWriter.flush() ; } catch (Exception e) { // TODO: handle exception } } }) ; } //监听服务器发来的消息 private Runnable mRunnable = new Runnable() { @Override public void run() { while (true) { try { if ((mStrMsg =mBufferedReader.readLine())!=null ){ mStrMsg +="\n";//换行 mHandler.sendMessage(mHandler.obtainMessage()) ; } } catch (Exception e) { // TODO: handle exception } } } }; //更新用户界面 Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); mEditText1.append(mStrMsg) ; } } ; }
PC客户端
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TcpClient { private static final int PORT =8888; private static ExecutorService executorService = Executors.newCachedThreadPool(); public static void main(String args []){ new TcpClient() ; } public TcpClient(){ try { Socket socket = new Socket("",PORT) ; executorService.execute(new ThreadClient(socket)) ; } catch (Exception e) { // TODO: handle exception } } static class ThreadClient implements Runnable{ private Socket socket ; public ThreadClient(Socket socket){ this.socket = socket ; } public void run() { try { BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream())) ; PrintWriter pw = new PrintWriter(socket.getOutputStream(), true) ; String msg ="" ; while (true) { msg = br.readLine() ; pw.println(msg) ; if (msg.trim().equals("exit")){ pw.close() ; br.close() ; socket.close() ; executorService.shutdownNow() ; } } } catch (Exception e) { e.printStackTrace(); } } } }