Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Java Socket 編程(一):用 Socket 實現服務器與客戶端的消息推送

編輯:關於 Android 程式設計

網上關於 Socket 聊天的例子很多,但仔細看下去,能完整跑通、邏輯又清晰的並不多。我打算用幾篇的篇幅,寫一個從簡到繁的完整 Socket 案例。這一篇先從最小可用版本開始:服務器與客戶端建立連接,雙向收發消息。

目標很明確:客戶端能向服務器發消息,服務器也能主動向客戶端推送消息。

一、Java 端:聊天服務器

1. 常量定義

把 IP 和端口集中管理,服務器與客戶端共用同一份定義。

public class SocketUrls {
    public final static String IP = "192.168.1.110";
    public final static int PORT = 8888;
}

2. 程序入口

public class Main {
    public static void main(String[] args) throws Exception {
        new ChatServer().initServer();
    }
}

3. 實體類

public class UserInfoBean implements Serializable {
    private static final long serialVersionUID = 1L;

    private long userId;        // 用戶 id
    private String userName;    // 用戶名
    private String likeName;    // 昵稱
    private String userPwd;     // 密碼
    private String userIcon;    // 頭像
    // get / set 省略
}
public class MessageBean extends UserInfoBean {
    private static final long serialVersionUID = 1L;

    private long messageId;     // 消息 id
    private long groupId;       // 群 id
    private boolean isGoup;     // 是否群消息
    private int chatType;       // 1文本 2圖片 3小視頻 4文件 5位置 6語音 7視頻通話
    private String content;     // 文本內容
    private String errorMsg;    // 錯誤描述
    private int errorCode;      // 錯誤碼
    // get / set 省略
}

消息用 Gson 序列化成 JSON 傳輸。這裡有個實務判斷:JSON 的可讀性好、跨語言方便,代價是帶寬開銷大;如果追求性能,Protobuf 會是更好的選擇。入門階段先用 JSON 把邏輯跑通。

4. ChatServer:服務器主體

public class ChatServer {

    private static ServerSocket server;
    public Gson gson = new Gson();

    public void initServer() {
        try {
            server = new ServerSocket(SocketUrls.PORT);
            createMessage();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void createMessage() {
        try {
            System.out.println("等待用戶接入 : ");

            // accept() 是阻塞的,直到有客戶端連上
            Socket socket = server.accept();
            System.out.println("用戶接入 : " + socket.getPort());

            // 開一個線程去 accept 下一個客戶端,否則第二個用戶永遠進不來
            new Thread(new Runnable() {
                public void run() {
                    createMessage();
                }
            }).start();

            OutputStream output = socket.getOutputStream();
            BufferedReader bff = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));

            // 一個線程專門讀控制台輸入,實現服務器主動推送
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String buffer;
                        while (true) {
                            BufferedReader strin = new BufferedReader(
                                    new InputStreamReader(System.in));
                            buffer = strin.readLine();
                            // readLine 以換行符為結束標誌,所以必須補上
                            buffer += "\n";
                            output.write(buffer.getBytes("utf-8"));
                            output.flush();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            // 主流程負責讀取該客戶端發來的消息
            String line;
            while (true) {
                Thread.sleep(500);
                while ((line = bff.readLine()) != null) {
                    MessageBean messageBean = gson.fromJson(line, MessageBean.class);
                    System.out.println("用戶 : " + messageBean.getUserName());
                    System.out.println("內容 : " + messageBean.getContent());
                }
            }
        } catch (Exception e) {
            System.out.println("錯誤 : " + e.getMessage());
        }
    }
}

這裡有兩個關鍵點。第一,accept 必須放在子線程裡遞歸調用,否則服務器只能服務一個客戶端。第二,readLine() 是阻塞的,它以換行符作為一條消息的邊界,讀不到換行就一直卡在那裡。這個特性後面在客戶端也必須照顧到。

二、Android 端:移動客戶端

1. Application 持有全局狀態

public class ChatAppliaction extends Application {
    public static ChatServer chatServer;
    public static UserInfoBean userInfoBean;

    @Override
    public void onCreate() {
        super.onCreate();
    }
}

記得在 AndroidManifest.xml 中通過 android:name 指定這個類,否則不會生效。另外,網絡通信需要 INTERNET 權限。

2. IP 與端口

與服務器保持一致的 SocketUrls。

3. 實體類

同服務器端。

4. 布局

登錄界面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/chat_name_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="用戶名" />

    <EditText
        android:id="@+id/chat_pwd_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="密碼"
        android:inputType="numberPassword" />

    <Button
        android:id="@+id/chat_login_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登錄" />

</LinearLayout>

聊天界面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.9">

        <LinearLayout
            android:id="@+id/chat_ly"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />

    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/chat_et"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8" />

        <Button
            android:id="@+id/send_btn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:text="發送" />

    </LinearLayout>

</LinearLayout>

順手提一個原始示例裡的小問題:ScrollView 的直接子容器的 layout_height 應寫 wrap_content 而不是 match_parent,否則內容超出時無法正常滾動。

5. LoginActivity

public class LoginActivity extends AppCompatActivity {

    private EditText chat_name_text, chat_pwd_text;
    private Button chat_login_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        chat_name_text = (EditText) findViewById(R.id.chat_name_text);
        chat_pwd_text  = (EditText) findViewById(R.id.chat_pwd_text);
        chat_login_btn = (Button) findViewById(R.id.chat_login_btn);

        chat_login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getLogin(chat_name_text.getText().toString().trim(),
                             chat_pwd_text.getText().toString().trim())) {
                    getChatServer();
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                }
            }
        });
    }

    private boolean getLogin(String name, String pwd) {
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) return false;
        return name.equals("admin") && pwd.equals("123123123a");
    }

    private void getChatServer() {
        ChatAppliaction.chatServer = new ChatServer();
    }
}

6. MainActivity

public class MainActivity extends AppCompatActivity {

    private LinearLayout chat_ly;
    private TextView left_text, right_view;
    private EditText chat_et;
    private Button send_btn;

    private ViewGroup.LayoutParams layoutParams =
            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                       ViewGroup.LayoutParams.WRAP_CONTENT);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        chat_ly  = (LinearLayout) findViewById(R.id.chat_ly);
        chat_et  = (EditText) findViewById(R.id.chat_et);
        send_btn = (Button) findViewById(R.id.send_btn);

        send_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChatAppliaction.chatServer.sendMessage(chat_et.getText().toString().trim());
                chat_ly.addView(initRightView(chat_et.getText().toString().trim()));
            }
        });

        // 接收後台推送的消息並刷新界面
        ChatAppliaction.chatServer.setChatHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    chat_ly.addView(initLeftView(msg.obj.toString()));
                }
            }
        });
    }

    private View initRightView(String messageContent) {
        right_view = new TextView(this);
        right_view.setLayoutParams(layoutParams);
        right_view.setGravity(View.FOCUS_RIGHT);
        right_view.setText(messageContent);
        return right_view;
    }

    private View initLeftView(String messageContent) {
        left_text = new TextView(this);
        left_text.setLayoutParams(layoutParams);
        left_text.setGravity(View.FOCUS_LEFT);
        left_text.setText(messageContent);
        return left_text;
    }
}

7. 客戶端 ChatServer

public class ChatServer {

    private Socket socket;
    private Handler handler;
    private MessageBean messageBean;
    private Gson gson = new Gson();

    PrintWriter printWriter;
    InputStream input;
    OutputStream output;
    DataOutputStream dataOutputStream;

    public ChatServer() {
        initMessage();
        initChatServer();
    }

    public void setChatHandler(Handler handler) {
        this.handler = handler;
    }

    private void initChatServer() {
        receiveMessage();
    }

    private void initMessage() {
        messageBean = new MessageBean();
        messageBean.setUserId(1);
        messageBean.setMessageId(1);
        messageBean.setChatType(1);
        messageBean.setUserName("admin");
        ChatAppliaction.userInfoBean = messageBean;
    }

    public void sendMessage(String contentMsg) {
        try {
            if (socket == null) {
                Message message = handler.obtainMessage();
                message.what = 1;
                message.obj = "服務器已經關閉";
                handler.sendMessage(message);
                return;
            }

            byte[] str = contentMsg.getBytes("utf-8");
            messageBean.setContent(new String(str));
            String messageJson = gson.toJson(messageBean);

            // 服務器的 readLine() 是阻塞讀,讀不到換行符就一直卡著
            // 所以必須在 JSON 末尾補上換行,告訴對方這條消息結束了
            messageJson += "\n";

            output.write(messageJson.getBytes("utf-8"));
            output.flush();
        } catch (Exception e) {
            Log.e("test", "錯誤:" + e.toString());
        }
    }

    private void receiveMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket(SocketUrls.IP, SocketUrls.PORT);

                    printWriter     = new PrintWriter(socket.getOutputStream());
                    input           = socket.getInputStream();
                    output          = socket.getOutputStream();
                    dataOutputStream = new DataOutputStream(socket.getOutputStream());

                    BufferedReader bff = new BufferedReader(new InputStreamReader(input));

                    String line;
                    while (true) {
                        Thread.sleep(500);
                        while ((line = bff.readLine()) != null) {
                            Log.i("socket", "內容 : " + line);
                            Message message = handler.obtainMessage();
                            message.obj = line;
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                        if (socket == null) break;
                    }

                    output.close();
                    input.close();
                    socket.close();
                } catch (Exception e) {
                    Log.e("test", "錯誤:" + e.toString());
                }
            }
        }).start();
    }
}

這段代碼裡最需要理解的是為什麼處處都要加 \n。服務器和客戶端都用 readLine() 讀數據,而它的終止條件是換行符或流結束。如果發送方不補換行,接收方就會永遠阻塞在那一行,看起來像是「消息發不出去」,實際上是對方還在等。

另外注意:Socket 的讀取必須在子線程,而 UI 更新必須在主線程,兩者之間靠 Handler 銜接。這個模式在後續所有篇章裡都會反覆出現。

寫到這裡,具備了什麼

這個 demo 已經能實現手機端向服務器發消息、服務器向手機端推送消息。嚴格說它算「推送」的雛形,真正的推送系統遠比這複雜——要處理連接保持、心跳保活、離線消息、多設備同步等一大堆問題。

但作為 Socket 的入門,它足夠展現核心思想:服務端異步接受連接,雙向流各自獨立,消息邊界需要顯式約定,線程之間通過消息隊列協作。

後續幾篇會在這個基礎上依次加上:客戶端與客戶端聊天、群聊、位置共享、圖文混排,以及圖片、小視頻、語音的傳輸。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved