Android-Socket实现简易聊天室

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.br.MySocketActivity">

    <TextView
            android:gravity="center"
            android:text="简易聊天室"
            android:textSize="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <TextView
            android:layout_width="match_parent"
            android:layout_height="150dp" android:id="@+id/textShow"/>
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editText"/>
    <Button
            android:text="发送消息"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/sendButton"/>
</LinearLayout>

Server端

package com.br;

import android.app.Service;
import android.util.Log;

import java.io.*;
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 Server {

    private static final int PORT = 12345;
    private List<Socket> socketList = new ArrayList<>();
    private ServerSocket serverSocket = null;
    private ExecutorService executorService = null;

    public static void main(String[] args)  {

        new Server();
    }


    public Server(){
        try{
            serverSocket = new ServerSocket(PORT);
            //创建线程池
            executorService = Executors.newCachedThreadPool();
            System.out.println("服务端运行中...\n");
            Socket client = null;
            while (true){
                //返回一个与连接客户端Socket对应的Socket
                client = serverSocket.accept();
                socketList.add(client);
                executorService.execute(new Service(client));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class Service implements Runnable{

        private Socket socket;
        private BufferedReader in = null;
        private String msg="";

        public Service(Socket socket){
            this.socket = socket;
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                msg = "用户: "+this.socket.getInetAddress()+" 加入了聊天室; "
                        +"当前在线人数:"+socketList.size();
                this.sendMsg();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try{
                while(true){
                    if((msg = in.readLine())!=null){
                        if(msg.equals("bye")){
                            System.out.println("------------");
                            socketList.remove(socket);
                            in.close();
                            msg = "用户: "+this.socket.getInetAddress()+" 退出了聊天室\n"
                                    +"当前在线人数:"+socketList.size();
                            socket.close();
                            this.sendMsg();
                            break;
                        }
                        else {
                            msg ="用户: "+ socket.getInetAddress()+" : "+msg;
                            this.sendMsg();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        //给每个连上服务端的客户端发送消息
        public void sendMsg(){
            System.out.println("msg:"+msg);
            int num = socketList.size();
            for (int i = 0; i <num ; i++) {
                Socket mSocket = socketList.get(i);
                PrintWriter out = null;
                try {
                    out = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(mSocket.getOutputStream(),"UTF-8")),true);
                    out.println(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

Client端

package com.br;

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.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class MySocketActivity extends AppCompatActivity implements Runnable{

    private static final int SUCCESS = 0x123;
    private static final String HOST = "127.0.0.1"; //本机ip
    private static final int PORT = 12345;
    private TextView textShow;
    private EditText editText;
    private Button sendButton;
    private Socket socket = null;
    private BufferedReader in = null;
    private PrintWriter out = null;
    private String content = "";
    private StringBuilder builder = null;

    public Handler handler = new Handler(){
        public void handleMessage(Message msg){
            if(msg.what == SUCCESS){
                builder.append(content);
                textShow.setText(builder.toString());
            }
        }
    };

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

        builder = new StringBuilder();
        textShow = findViewById(R.id.textShow);
        editText = findViewById(R.id.editText);
        sendButton = findViewById(R.id.sendButton);

        //当程序一开始运行的时候就实例化Socket对象,与服务端进行连接,获取输入输出流
        //4.0以后不能再主线程中进行网络操作,所以需要另外开辟一个线程
        new Thread(){
            @Override
            public void run() {
                try{
                    //创建socket对象,指定主机地址和端口
                    socket = new Socket(HOST,PORT);
                    //获取输入流
                    in = new BufferedReader(new InputStreamReader
                            (socket.getInputStream(),"UTF-8"));
                    //获取输出流
                    out = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(socket.getOutputStream())),true);
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg = editText.getText().toString();
                if(socket.isConnected()){
                    if(!socket.isOutputShutdown()){
                        out.println(msg);
                    }
                }
            }
        });
        new Thread(MySocketActivity.this).start();
    }

    @Override
    public void run() {
        try{
            //先让此线程睡眠一秒,让onCreate方法里的线程获取到socket
            Thread.sleep(1000);
            while (true){
                if(socket.isConnected()){ //判断socket是(返回true)否成功连接过
                    if(!socket.isInputShutdown()){  //判断socket是否关闭
                        if((content = in.readLine())!=null){
                            content+="\n";
                            handler.sendEmptyMessage(SUCCESS);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值