欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【达内课程】利用Socket实现群聊

程序员文章站 2024-01-03 09:02:58
...

思路
【达内课程】利用Socket实现群聊
服务端实现
【达内课程】利用Socket实现群聊
客户端实现
【达内课程】利用Socket实现群聊
注意
【达内课程】利用Socket实现群聊

按照以上思路完成服务端
ChatServer

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ChatServer {
    private List<Socket> sockets = new ArrayList<Socket>();
    /**
     * 开启服务
     * @throws IOException 
     */
    public void startServer() throws IOException{
        System.out.println("服务已启动...");
        //启动服务
        ServerSocket ss = new ServerSocket(8888);
        //不断接收从客户端发来的消息
        while(true){
            //阻塞执行,接收客户端连接
            Socket socket = ss.accept();
            sockets.add(socket);
            //想要并发处理的话,需要开启线程
            new WorkThread(socket).start();
        }
    }

     /**
     * 工作线程
     * 接收客户端的消息,并给每个线程发一遍
     */
    class WorkThread extends Thread{
        private Socket socket;
        public WorkThread(Socket socket){
            this.socket = socket;
        }
        public void run(){
            try {
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                while (true){
                    String message = dis.readUTF();
                    //给每一个客户端都发一遍
                    for(int i=0;i<sockets.size();i++){
                        Socket s = sockets.get(i);
                        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                        dos.writeUTF(message);
                        dos.flush();
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                //当开启一条线程后,线程会等待客户端发消息
                //在等待的过程中,可能出现异常,比如连接中断,就会抛出connection reset的异常
                //就会走到这里

                System.out.println("连接中断");
                //把当前socket对象从集合中移除
                sockets.remove(socket);
            }
        }
    }

    public static void main(String[] args){
        ChatServer server = new ChatServer();
        try {
            server.startServer();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

布局文件
activity_main

<RelativeLayout 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="com.example.xx.myapplication.MainActivity">

    <EditText
        android:id="@+id/et_ip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/btn_ip" />

    <Button
        android:id="@+id/btn_ip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="确定" />

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/btn_message"
        android:layout_below="@+id/btn_ip" />

    <Button
        android:id="@+id/btn_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="确定" />

    <EditText
        android:id="@+id/et_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@+id/btn_message" />
</RelativeLayout>

MainActivity

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_ip;
    private EditText et_message;
    private Button btn_ip;
    private Button btn_message;
    private ListView listview;
    private Socket socket;

    private DataInputStream dis;
    private DataOutputStream dos;

    private List<String> messages = new ArrayList<>();
    private ArrayAdapter<String> adapter;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_CONNECT_SUCCESS://连接成功
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    et_ip.setEnabled(false);
                    btn_ip.setEnabled(false);
                    break;
                case HANDLER_MESSAGE_RECEIVED://接受到消息
                    String message = (String)msg.obj;
                    messages.add("小明:"+message);
                    //更新adapter
                    adapter.notifyDataSetChanged();
                    //显示最后一条
                    listview.setSelection(messages.size()-1);
                    break;
            }
        }
    };

    private static final int HANDLER_CONNECT_SUCCESS = 1;
    private static final int HANDLER_MESSAGE_RECEIVED = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setViews();
        //设置适配器
        setAdapter();
    }

    private void setAdapter() {
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,messages);
        listview.setAdapter(adapter);
    }

    private void setViews() {
        et_ip = findViewById(R.id.et_ip);
        et_message = findViewById(R.id.et_message);
        btn_ip = findViewById(R.id.btn_ip);
        btn_message = findViewById(R.id.btn_message);
        listview = findViewById(R.id.listview);

        btn_ip.setOnClickListener(this);
        btn_message.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_ip:
                //建立连接
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            connect();
                        } catch (IOException e) {
                            e.printStackTrace();
                            //连接建立失败
                        }
                    }
                }.start();
                break;
            case R.id.btn_message:
                //发送消息
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            sendMessage();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
        }
    }

    private void sendMessage() throws IOException {
        String text = et_message.getText().toString();
        dos.writeUTF(text);
        dos.flush();
    }

    /**
     * 读取服务端发回的消息的工作线程
     */
    class ReadThread extends Thread {
        //run方法执行完毕后,线程也就销毁了
        //垃圾回收机制会回收
        @Override
        public void run() {
            /*while (true){
                try {
                    String message = dis.readUTF();
                } catch (IOException e) {
                    e.printStackTrace();
                    //当断开连接,并不会跳出while循环,所以改成以下写法
                }
            }*/
            try {
                while (true) {
                    String message = dis.readUTF();
                    Log.i("info","message:"+message);
                    //更新ListView,给handler发消息
                    Message msg = new Message();
                    msg.what = HANDLER_MESSAGE_RECEIVED;
                    msg.obj = message;
                    handler.sendMessage(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
                //连接异常,断开
                Log.e("error", "连接出错,读不了数据了,看着办吧");
            }
        }
    }

    private void connect() throws IOException {
        String ip = et_ip.getText().toString();
        socket = new Socket(ip, 8888);

        dis = new DataInputStream(socket.getInputStream());
        dos = new DataOutputStream(socket.getOutputStream());
        //连接成功,发消息给主线程Handler 更新UI
        handler.sendEmptyMessage(HANDLER_CONNECT_SUCCESS);
        //启动读取消息的工作线程
        new ReadThread().start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(socket!=null){
            try {
                //socket关掉后,流也就关掉了
                //而客户端还有线程正等着读取数据,所以也需要处理下
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

增加权限
AndroidManifest

    <uses-permission android:name="android.permission.INTERNET"/>

运行步骤
1、用Eclipse运行ChatServer
【达内课程】利用Socket实现群聊

2、查看自己电脑ip
cmd中执行ipconfig
【达内课程】利用Socket实现群聊
3、修改MainActivity中,以下代码,把message前增加一个称呼,例如“小明”,运行在一台模拟机中

private void sendMessage() throws IOException {
        String text = et_message.getText().toString();
        dos.writeUTF("小红:\n"+text);
        dos.flush();
    }

输入刚才的ip地址,保证连接成功
【达内课程】利用Socket实现群聊

4、修改MainActivity中3步骤代码中的称呼,改为“小红”,运行在另一台模拟机中,输入相同ip保证连接成功
【达内课程】利用Socket实现群聊

5、开始尬聊

【达内课程】利用Socket实现群聊

相关标签: socket

上一篇:

下一篇: