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

文章目录

思路

【完成群聊天室】
服务端:
每当接收到客户端发来的消息后,需要给每一个在线的客户都输出一遍

List<Socket> sockets;

main{
	socket= ss.accept();
	sockets.add(socket);
	new Thread(){
		run(){
			
		}
	}.start();
}

客户端:
建立连接、发送消息、接收并显示消息

注意:
网络编程注意事项:
1、所有网络操作都需要在工作线程中执行
2、网络操作需要添加权限

实现

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

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) {
                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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <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_alignParentRight="true"
        android:layout_alignParentBottom="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

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、用 IntelliJ IDEA 运行ChatServer
在这里插入图片描述

2、查看自己电脑 ip
cmd 中执行ipconfig
在这里插入图片描述

3、修改MainActivity中,以下代码,把 message 前增加一个称呼,例如“小明”,运行在一台模拟机中

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

4、修改 MainActivity 中 3 步骤代码中的称呼,改为“小红”,运行在另一台模拟机中

5、都输入 ip 地址确保连接成功

5、开始尬聊

在这里插入图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package windows; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.ClientPNames; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; /** * 核心功能封装类 * @author 冯晋强 * */ public class TmoocOperate { static String sessionid; static CloseableHttpResponse response = null; static CloseableHttpClient httpclient = null; //静态块 static{ // 创建提交数据对象 httpclient = HttpClients.createDefault(); } /** * 处理在线疑答贴子列表源码数据 * @author 刑保政 */ public static String[][] splist(String Str) { Str = Str.substring(Str.lastIndexOf("<ul>") + 4, Str.lastIndexOf("</ul>")).replaceAll("\\s", ""); String[] lis = Str.split("</li>");// 所有记录的数组 String[] jilu = null;// 单条记录的数组 String[][] allMsg = new String[lis.length - 1][4]; // 创建一个二维数组保存处理后的数据,其中每个一维数组中包含一个记录,每个二维数组中包含每条数据的信息 // allMsg[i][0]:标题; allMsg[i][1]:时间 allMsg[2]:处理状态 for (int i = 0; i < lis.length - 1; i++) {// 遍历所有记录,取出每一条记录 String ss = lis[i];// 取出每一条记录 jilu = ss.split("(</a></span>|</span>)"); // 每条记录分割成3部分 jilu[0]:标题 jilu[2]:时间 jilu[3]:处理状态 for (int j = 0; j < jilu.length; j++) {// 由于数据中还含有部分额外代码,遍历所有记录筛选数据 String msg = jilu[j];// 单条记录中的每一个数据 System.out.println(msg); msg = msg.substring(msg.lastIndexOf(">") + 1, msg.length()); String uid = jilu[0].substring(jilu[0].lastIndexOf("(") + 1, jilu[0].lastIndexOf(")")); allMsg[i][j] = msg; allMsg[i][3] = uid; } } return allMsg; } /** * 处理在线疑答帖子内容源码数据 * @author 刑保政 */ public static String[] splist1(String all) { String queStr = all.substring(all.indexOf("<div class=\"quesdetail\""),all.indexOf("<div id=\"answers\"")); // .replaceAll("\\s","");//处理源码筛选字符串,只获取含有问题标题的内容 // System.out.println(queStr);//测试标题部分字符串 String[] queArr = queStr.split("(</span|</pre|</div>)"); for(int i=0;i<queArr.length;i++){ String msg = queArr[i]; msg = msg.substring(msg.lastIndexOf(">")+1, msg.length()); if(i == 5){ msg = msg.substring(msg.indexOf(":")+1).trim(); } queArr[i] = msg; } String[] que = new String[4];//保存最终标题内容的数组 que[0] = queArr[1]; que[1] = queArr[3]; que[2] = queArr[4]; que[3] = queArr[5]; for(int i=0;i<2;i++){ que[i] = que[i].replaceAll("<","<"); que[i] = que[i].replaceAll(">",">"); que[i] = que[i].replaceAll(" "," "); que[i] = que[i].replaceAll("&","&"); que[i] = que[i].replaceAll(""","\""); que[i] = que[i].replaceAll("©","@"); que[i] = que[i].replaceAll("®","商标"); } return que; } // 回复帖子方法包 public static boolean SetTitle1(String message,String uid) { try { // url提交地址 HttpPost httpPost = new HttpPost("http://tts8.tmooc.cn/onlinefaq/anwser"); // 组合数据包 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("questionId", uid)); nvps.add(new BasicNameValuePair("context", message)); // 设置数据包 httpPost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); // 提交数据包 response = httpclient.execute(httpPost); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); System.out.println(str); if(str.indexOf("true")!=-1){ return true; }else{ return false; } } catch (ClientProtocolException e) { System.out.println("数据包提交失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } // 发送帖子方法包 public static boolean SetTitle(String tilte, String message) { try { // url提交地址 HttpPost httpPost = new HttpPost("http://tts8.tmooc.cn/onlinefaq/add"); // 组合数据包 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("title", tilte)); nvps.add(new BasicNameValuePair("context", message)); // 设置数据包 httpPost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); // 提交数据包 response = httpclient.execute(httpPost); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); System.out.println(str); if(str.indexOf("true")!=-1){ return true; }else{ return false; } } catch (ClientProtocolException e) { System.out.println("数据包提交失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } /** * * @author 刑保政 */ public static Vector<Vector<String>> getAite(Vector<Vector<String>> vvs){ /** 保存所有姓名的集合,因为回帖人中有重复数据,所以这里用Set去除重复 */ Set<String> usersSet = new HashSet<String>(); /** 保存所有回帖内容的集合 */ List<String> texts = new ArrayList<String>(); /* 遍历回帖集合,分别取出每一条记录中的回帖人和回帖内容,并添加到 * 对应的集合中,方便下一步遍历筛选 */ for(int i=0;i<vvs.size();i++){ Vector<String> v = vvs.get(i); String user = v.get(1); String text = v.get(3); usersSet.add(user); texts.add(text); } // System.out.println(users);//测试回帖人集合 // System.out.println(texts);//测试回帖内容集合 String[] users = new String[usersSet.size()]; usersSet.toArray(users);//将usersSet回帖人集合转为数组方便遍历 // System.out.println(Arrays.toString(users));//测试回帖人数组 /* 遍历回帖人数组,取出每一个回帖人, * 遍历每一条回帖内容,判断内容是否以@+回帖人开头,(当前设置@只能在开头有用,中间的不予考虑) * 若是则提取该回帖人并添加到当前楼层集合中 */ for(int i=0;i<users.length;i++){ String user = users[i]; for(int j=0;j<texts.size();j++){ String text = texts.get(j); if(text.startsWith("@" + user)){ // System.out.println(text); vvs.get(j).add("@" + user); } } } return vvs;//将处理后的集合返回 } /** * * @author 刑保政 */ public static Vector<Vector<String>> getAnswer(String all){ all = all.substring(all.indexOf("<div id=\"answers\""), all.indexOf("<div id=\"appendQues\"")); //抽取数据片段(答案部分) // System.out.println(all); String[] ansArr = all.split("<div class=\"answer");//分割成存储单条回帖的数组 String[] answer = null;//每一条回帖数组 Vector<Vector<String>> vvs = new Vector<Vector<String>>();//创建二维集合保存信息 /* * 遍历回帖集合,取出每一条回帖记录,分割成一组回帖信息元素, * 进行处理后添加进二维集合 */ for(int i = 1;i<ansArr.length;i++){ String ansStr = ansArr[i]; answer = ansStr.split("(</span>|</pre>)"); vvs.add(new Vector<String>()); vvs.get(i-1).add(i + "");//楼层数 for(int j=0;j<answer.length-1;j++){//处理每条回帖的信息 String msg = answer[j].trim(); msg = msg.substring(msg.lastIndexOf(">")+1,msg.length()).trim(); if(j == 1){//对时间单独进行处理一下 msg = msg.substring(msg.indexOf("(")+1,msg.length()-1).trim(); } vvs.get(i-1).add(msg);//添加进二维集合 } } vvs = getAite(vvs); return vvs; } // 读取在线疑答帖子内容源码数据 public static String Get_title(String uid) { try { // url提交地址 HttpGet httpGet = new HttpGet("http://tts8.tmooc.cn/onlinefaq/detail/"+ uid); // 提交数据包 response = httpclient.execute(httpGet); // 取出cookie System.out.println(response.getFirstHeader("Cookie")); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); return str; } catch (ClientProtocolException e) { System.out.println("数据包提交失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } // 读取在线疑答帖子列表源码数据 public static String Get_tilte() { try { // url提交地址 HttpGet httpGet = new HttpGet("http://tts8.tmooc.cn/onlinefaq/questionList"); // 提交数据包 response = httpclient.execute(httpGet); System.out.println("第七次请求成功"); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); return str; } catch (ClientProtocolException e) { System.out.println("数据包提交失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } // 初始化登陆,判断是否需要登陆验证码 暂时未完善 public static void GetCode(String user) { CloseableHttpClient httpclient = null; CloseableHttpResponse response2 = null; try { // url提交地址 HttpPost httpPost = new HttpPost("http://tmooc.cn/login/loginTimes"); // 组合数据包 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("login_name", user)); // 设置数据包 httpPost.setEntity(new UrlEncodedFormEntity(nvps)); // 创建提交数据对象 httpclient = HttpClients.createDefault(); // 提交数据包 response2 = httpclient.execute(httpPost); // 读取返回数据信息 String str = EntityUtils.toString(response2.getEntity()); System.out.println(str); TmoocOperate.SetTitle("今天的表示没怎么听懂", "你们呢。。。"); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { response2.close(); httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } // 登陆Tmooc方法 public static boolean Tmooc_Login(String user, String pass) { try { // url提交地址 HttpPost httpPost = new HttpPost("http://tmooc.cn/login"); // 组合数据包 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("login_name", user)); nvps.add(new BasicNameValuePair("password", Login_MD5(pass).toLowerCase())); nvps.add(new BasicNameValuePair("type", "P")); nvps.add(new BasicNameValuePair("uuid","E1CC4286A419C899CCBF6A04E5A1CF02")); // 设置数据包 httpPost.setEntity(new UrlEncodedFormEntity(nvps)); // 提交数据包 response = httpclient.execute(httpPost); // 读取返回数据信息 String str = EntityUtils.toString(response.getEntity()); //判断是否登陆成功 if (str.indexOf(user) != -1) { sessionid = str.substring(14, str.indexOf("|P#")); // 取出cookie方法 这里用不到 //Cookie = response2.getFirstHeader("Set-Cookie").toString(); // url提交地址 HttpGet httpGet = new HttpGet("http://tmooc.cn/login/hadlogin/"+ sessionid); // 提交数据包 response = httpclient.execute(httpGet); // url提交地址 httpGet = new HttpGet("http://tts8.tmooc.cn/user/myTTS?sessionId=" + sessionid + "&date="); // 提交数据包 response = httpclient.execute(httpGet); return true; } } catch (UnsupportedEncodingException e) { System.out.println("设置数据包出错"); e.printStackTrace(); } catch (ClientProtocolException e) { System.out.println("提交数据异常"); e.printStackTrace(); } catch (IOException e) { System.out.println("其他错误"); e.printStackTrace(); } return false; } //utf-8编码 public static String bm_utf8(String Str){ String bmjg = null; try { bmjg = URLEncoder.encode(Str, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return bmjg; } // 登陆tmooc时md5加密方法 public final static String Login_MD5(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = s.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { e.printStackTrace(); return null; } } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值