Android之socket服務端

來源:互聯網
上載者:User

標籤:

首先在確保服務端與用戶端是相通的,ping不通肯定連不上。

TCP服務端代碼

package com.example.tcp_server;import java.io.DataInputStream;import java.io.IOException;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;import android.annotation.SuppressLint;import android.os.Handler;import android.os.Message;import android.os.StrictMode;import android.util.Log;@SuppressLint("NewApi")public class tcpservice implements Runnable{        //伺服器連接埠    private static final int SERVERPORT = 2001;     //儲存所有用戶端Socket連線物件    private static List<Socket> mClientList = new ArrayList<Socket>();     //線程池    private ExecutorService mExecutorService;      //ServerSocket對象    private ServerSocket mServerSocket;      private static PrintWriter mPrintWriter;    private static String  mStrMSG;    public tcpservice()    {        try        {            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());            //設定伺服器連接埠            mServerSocket = new ServerSocket(SERVERPORT);            //建立一個線程池            mExecutorService = Executors.newCachedThreadPool();            Log.e("tcpservice", "start...");            //用來臨時儲存用戶端串連的Socket對象            new Thread(tcpservice.this).start();                    }        catch (IOException e)        {            Log.e("tcpservice", e.toString());            e.printStackTrace();        }    }    //接收線程發送過來資訊,並用TextView顯示    public static Handler mHandler = new Handler() {        public void handleMessage(Message msg) {            super.handleMessage(msg);            Log.e("伺服器說:", mStrMSG);            MainActivity.AppendText("伺服器說:"+mStrMSG);            }    };     //每個用戶端單獨開啟一個線程    static class ThreadServer implements Runnable    {        private Socket            mSocket;        private DataInputStream dinput;        public ThreadServer(Socket socket) throws IOException        {            this.mSocket = socket;            dinput=new DataInputStream(socket.getInputStream());            SendToClient("hello,tcp server...");        }        public void run()        {            try            {                byte[] bbuf = new byte[10000];                while (true) {                                        if (!mSocket.isClosed()) {                        if (mSocket.isConnected()) {                            if (!mSocket.isInputShutdown()) {                                int length = dinput.read(bbuf);                                   mStrMSG = new String(bbuf, 0, length, "gb2312");                                   mStrMSG += "\n";                                   mHandler.sendMessage(mHandler.obtainMessage());                            }                        }                    }                }            }            catch (IOException e)            {                e.printStackTrace();            }        }    }    public static  void SendToClient(String msg){        try{            for (Socket client : mClientList)            {                mPrintWriter = new PrintWriter(client.getOutputStream(), true);                mPrintWriter.println(msg);            }        }        catch(Exception e){            Log.e("向用戶端發送訊息敗了", e.toString());        }    }    public void run() {        try{            Socket client = null;            while (true)            {                Log.e("tcpservice", "接收客戶串連");                //接收客戶串連並添加到list中                client = mServerSocket.accept();                 mClientList.add(client);                //開啟一個用戶端線程                mExecutorService.execute(new ThreadServer(client));            }        }        catch(Exception e){            Log.e("監聽用戶端", e.toString());        }    }}
tcpservice

 

前端

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:orientation="vertical" >      <EditText android:id="@+id/myinternet_tcpclient_EditText01"         android:layout_width="fill_parent"         android:layout_height="200px"         android:text="聊天記錄:\n" >     </EditText>      <EditText android:id="@+id/myinternet_tcpclient_EditText02"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="輸入要發送的內容" >     </EditText>      <LinearLayout android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:orientation="horizontal"         android:gravity="center" >          <Button android:id="@+id/myinternet_tcpclient_BtnSend"             android:layout_width="400px"             android:layout_height="wrap_content"             android:text="發送" />     </LinearLayout>  </LinearLayout>

後台

package com.example.tcp_server;import android.os.Bundle;import android.app.Activity;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity {    // 聲明對象    private Button  mSendButton;    private static EditText mEditText01;    private static  EditText mEditText02;    private static String TAG = "shit=";    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //啟動伺服器        new  tcpservice();        mSendButton = (Button) findViewById(R.id.myinternet_tcpclient_BtnSend);        mEditText01 = (EditText) findViewById(R.id.myinternet_tcpclient_EditText01);        mEditText02 = (EditText) findViewById(R.id.myinternet_tcpclient_EditText02);        //發送按扭註冊事件        mSendButton.setOnClickListener(new OnClickListener()        {            public void onClick(View v)            {                try                {                    // 取得編輯框中我們輸入的內容                    String str = mEditText02.getText().toString() + "\n";                    mEditText01.append("我說:"+str);                    //向用戶端發訊息                    tcpservice.SendToClient(str);                                    } catch (Exception e)                {                    Log.e(TAG, e.toString());                }            }        });    }    public static void AppendText(String msg){        mEditText01.append(msg);    }}
MainActivity

 

Android之socket服務端

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.