Java-Socket聊天功能之多线程实现发送与接受消息

该文章展示了一个使用Java编写的简单聊天程序,通过ServerSocket和Socket实现服务端和客户端的双向通信。程序利用多线程分别处理接收和发送消息,当输入空换行时,聊天结束。
摘要由CSDN通过智能技术生成

聊天场景:分别设置了服务端、客户端,两端均可接受消息及发送消息,输入空换行则结束聊天

服务端与客户端代码几乎一样,区别与serverSocket与 clientSocket的获取;

1.服务端代码

package 11111;

import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;

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


/**
 * @author Albert
 * @create 2023/4/7-下午 02:33
 * @description Test
 */
@Controller
public class MainFunction {
    static ServerSocket serverSocket;
    static Socket clientSocket;

    public static void main(String[] args) throws IOException {
        serverSocket = new ServerSocket(8888);
        System.out.println("服务器已启动,等待客户端连接...");

        //开启两个线程 一个接受信息 一个发送信息
        //自定义两个方法用于 接受/发送消息
        Thread thread = new Thread(sendInfo());
        thread.setName("发送");
        thread.start();
        Thread thread1 = new Thread(getInfo());
        thread1.setName("接受");
        thread1.start();

    }

    /**
     * 用于发送信息
     *
     * @return
     */
    private static Runnable sendInfo() {

        Runnable runnable = () -> {
            PrintWriter writer = null;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String s;
            try {
                //使用循环进行多次输入
                //当输入空换行,则跳出循环并停止输入,聊天结束
                while (!ObjectUtils.isEmpty(s = bufferedReader.readLine())) {
                    writer = new PrintWriter(clientSocket.getOutputStream(), true);
                    writer.println(s);
                }
                System.out.println("输入停止");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    writer.close();
                }
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (clientSocket != null) {
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        };

        return runnable;
    }

    /**
     * 用于接受信息
     *
     * @return
     */
    public static Runnable getInfo() {

        Runnable runnable = () -> {
            BufferedReader bufferedReader = null;
            try {
                //接受客户端发来的连接
                clientSocket = serverSocket.accept();
                System.out.println("服务连接");
                bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String s;
                //循环打印接受到的信息
                //当接受到空换行或空字符串则退出循环
                while (!ObjectUtils.isEmpty(s = bufferedReader.readLine())) {
                    System.out.println("客户端:" + s);
                }
                System.out.println("接受停止");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (clientSocket != null) {
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        return runnable;
    }

}

 2、客户端代码

package 11111;


import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * @author Albert
 * @create 2023/4/7-下午 02:33
 * @description Test
 */
@Controller
public class MainFunction2 {
    static Socket clientSocket;

    public static void main(String[] args) throws IOException {

        clientSocket = new Socket("localhost", 8888);

        Thread thread = new Thread(sendInfo());
        thread.setName("发送");
        thread.start();
        Thread thread1 = new Thread(getInfo());
        thread1.setName("接受");
        thread1.start();
    }

    private static Runnable sendInfo() {

        Runnable runnable = () -> {
            PrintWriter writer = null;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String s;
            try {
                while (!ObjectUtils.isEmpty(s = bufferedReader.readLine())) {
                    writer = new PrintWriter(clientSocket.getOutputStream(), true);
                    writer.println(s);
                }
                System.out.println("输入停止");

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    writer.close();
                }
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (clientSocket != null) {
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        };

        return runnable;
    }

    public static Runnable getInfo() {

        Runnable runnable = () -> {
            BufferedReader bufferedReader = null;
            try {
                bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String s;
                while (!ObjectUtils.isEmpty(s = bufferedReader.readLine())) {
                    System.out.println("服务端:" + s);
                }
                System.out.println("接受停止");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (clientSocket != null) {
                    try {
                        clientSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        return runnable;
    }

}

3、结果截图

先启动服务端,再启动客户端

客户端发分别发送两条信息给服务端

服务端均可接受到

 服务端发送信息给客户端

 

客户端也能接受

 客户端输入空换行结束聊天

服务端

 总结:聊天功能简单实现,后续还需针对业务进行优化

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值