java socket Server TCP服务端向指定客户端发送消息;可查看、断开指定连接的客户端;以及设置客户端最大可连接数量。

这篇具有很好参考价值的文章主要介绍了java socket Server TCP服务端向指定客户端发送消息;可查看、断开指定连接的客户端;以及设置客户端最大可连接数量。。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

实现思路

  • 首先需要知道java里如何创建一个Socket服务器端。
	//创建一个服务器端对象
	ServerSocket server = new ServerSocket(); 
	//绑定启动的ip和端口号
	server.bind(new InetSocketAddress("127.0.0.1",8082));
	//启动成功后,调用accept()方法阻塞,
	//当有客户端成功连接时会生成一个Socket对象用于通讯
	Socket socket = server.accept();

提示:注意server.accept()方法调用会阻塞,只有新的客户端连接后才返回一个新的socket对象。如果一直未连接那么会一直处于阻塞状态

  • 了解了如何创建一个socket服务器端后。那么如何实现给指定的连接客户端发送消息呢?首先我们可以知道只有有客户端连接服务器就会生成一个socket对象,socket对象中获取对应的输入输出流读取和写入就可以实现发送消息;也就是只要咱们把每次连接的socket保存起来,发送和接收数据就直接获取对应的socket就可以实现。
  • 总结一下。也就是需要循环调用 server.accept()阻塞方法,对每个连接的socket保存起来。并对每一个socket实现读取写入操作。为了可用性。对于服务器阻塞方法需要单独创建一个线程进行阻塞等待连接操作。并且对于每一个连接的客户端单独创建一个线程进行读写操作。
    好了话不多说直接上代码

项目源码

服务器端接口ISocketServer

/**
 * @description: 启用socket服务
 * @author liangxuelong
 * @date 2023/6/19 13:51
 * @version 1.0
 */
public interface ISocketServer {

    /**
     * @description: 启动服务
     * @author liangxuelong
     * @date 2023/6/19 13:53
     * @version 1.0
     */
    public void startServer();

    /**
     * @description: 停止服务
     * @author liangxuelong
     * @date 2023/6/19 13:53
     * @version 1.0
     */
    public void stopServer();

    /**
     * @description: 判断是否启动
     * @author liangxuelong
     * @date 2023/6/19 14:01
     * @version 1.0
     */
    public boolean isStart();

}

服务器端实现一个抽象类AbstractSocketServer,定义启动、停止。查看连接状态等方法

/**
 * @author liangxuelong
 *
 * @version 1.0
 * @description:
 * @date 2023/6/19 14:04
 */
public abstract class AbstractSocketServer implements ISocketServer{
    //服务器端口
    protected int port;
    //默认ip地址
    protected String ipAddress = "127.0.0.1";
    //默认最大连接数
    protected int maxConnectSize = 1;
    //当前连接状态
    protected boolean isConn = false;
    //java ServerSocket 对象
    private ServerSocket server;

    //保存所有连接通讯类
    protected ConcurrentHashMap<String,ICommunication> communications = new ConcurrentHashMap<>();

    public AbstractSocketServer(String ipAddress, int port) {
        this.ipAddress = ipAddress;
        this.port = port;
    }

    public AbstractSocketServer(int port) {
        this.port = port;
    }
    /**
     * @description: 启动服务
     * @author liangxuelong
     * @date 2023/6/19 16:14
     * @version 1.0
     */
    @Override
    public void startServer() {
        new Thread(() -> {
            try {
                if (isConn) {
                    stopServer();
                }
                server = new ServerSocket();
                //绑定数据连接地址端口号
                server.bind(new InetSocketAddress(ipAddress,port));
                //绑定成功设置当前服务器状态为true
                isConn = true;
                //循环等待客户端连接
                while(true){
                    //阻塞 等待socket client 连接
                    Socket socket = server.accept();
                    //生成连接通讯对象
                    SocketCommunication socketCommunication = new SocketCommunication(socket,this);
                    new Thread(() -> {
                        try {
                            addCommunication(socketCommunication);
                            socketCommunication.handle();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        removeCommunication(socket.getInetAddress().getHostAddress());
                    }).start();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }).start();
    }

    /**
     * @description: 停止服务
     * @author liangxuelong
     * @date 2023/6/19 16:14
     * @version 1.0
     */
    @Override
    public void stopServer(){
        if (server != null) {
            try {
                server.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            isConn = false;
            removeAllCommunication();
        }
    }


    /**
     * @description: 给所有连接发送
     * @author liangxuelong
     * @date 2023/6/19 16:51
     * @version 1.0
     */
    public void sendToALl(byte[] bytes){
        for (String ipAddress : communications.keySet()) {
            send(ipAddress,bytes);
        }
    }

    /**
     * @description: 给某个ip发送
     * @author liangxuelong
     * @date 2023/6/19 16:53
     * @version 1.0
     */
    public boolean send(String ip,byte[] bytes) {
        if (communications.get(ip) == null)
            return false;
        try {
            communications.get(ip).send(bytes);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @description: 当前是否启动 socket 服务端
     * @author liangxuelong
     * @date 2023/6/19 16:14
     * @version 1.0
     */
    @Override
    public boolean isStart() {
        return isConn;
    }

    /**
     * @description: 设置最大连接数量
     * @author liangxuelong
     * @date 2023/6/19 16:19
     * @version 1.0
     */
    public void setMaxConnectSize(int maxConnectSize) {
        this.maxConnectSize = maxConnectSize;
    }

    /**
     * @description: 获取当前连接数据
     * @param:
     * @return: void
     * @author liangxuelong
     * @date: 2023/6/19
     */
    public int getConnectSize(){
        return communications.size();
    }

    /**
     * @description: 获取当前所有连接的Ip地址
     * @param:
     * @return: void
     * @author liangxuelong
     * @date: 2023/6/19
     */
    public Set<String> getConnectIpAddress(){
        return communications.keySet();
    }

    /**
     * @description: 添加连接对象
     * @author liangxuelong
     * @date 2023/6/19 15:14
     * @version 1.0
     */
    protected void addCommunication(ICommunication communication) throws Exception {
        Socket socket = communication.getSocket();
        //判断是否超出最大连接数量,超出后断开连接
        if (maxConnectSize > communications.size()) {
            ICommunication iCommunication = communications.get(socket.getInetAddress()
                    .getHostAddress());
            if (iCommunication != null) {
                try {
                    iCommunication.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                communications.remove(socket.getInetAddress()
                        .getHostAddress());
            }
            communications.put(socket.getInetAddress()
                    .getHostAddress(),communication);
        } else {
            socket.close();
            throw new ConnectException(maxConnectSize);
        }
    }

    /**
     * @description: 移除连接对象
     * @author liangxuelong
     * @date 2023/6/19 15:14
     * @version 1.0
     */
    public void removeCommunication(String ip){
        ICommunication iCommunication = communications.get(ip);
        if (iCommunication != null) {
            try {
                iCommunication.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
            communications.remove(ip);
        }
    }

    /**
     * @description: 移除所有连接对象
     * @author liangxuelong
     * @date 2023/6/19 15:14
     * @version 1.0
     */
    public void removeAllCommunication(){
        for (String ipAddress : communications.keySet()) {
            removeCommunication(ipAddress);
        }
    }

}

服务器端实现抽象类创建SocketServer类

/**
 * @author liangxuelong
 * @version 1.0
 * @description: socket 服务启动类
 * @date 2023/6/19 15:53
 */
public class SocketServer extends AbstractSocketServer {

    public SocketServer(String ipAddress, int port) {
        super(ipAddress, port);
    }

    public SocketServer(int port) {
        super(port);
    }
}

客户端通讯接口ICommunication主要用于读写socket交互数据

public interface ICommunication {

    /**
     * @description: 获取当前连接的socket对象
     * @author liangxuelong
     * @date 2023/6/19 14:28
     * @version 1.0
     */
    public Socket getSocket();

    /**
     * @description: socket创建成功后读取数据
     * @author liangxuelong
     * @date 2023/6/19 14:29
     * @version 1.0
     */
    public void handle() throws Exception;

    /**
     * @description: 将读取到的数据统一处理
     * @author liangxuelong
     * @date 2023/6/19 14:29
     * @version 1.0
     */
    public void receive(Socket socket,byte[] data) throws Exception;
    
    /**
     * @description: 发送数据
     * @author liangxuelong
     * @date 2023/6/19 14:41
     * @version 1.0
     */
    public void send(byte[] data) throws Exception;

    /**
     * @description: 断开连接
     * @author liangxuelong
     * @date 2023/6/19 14:42
     * @version 1.0
     */
    public void disconnect() throws Exception;
}

客户端实现通讯接口ICommunication创建SocketCommunication对象用于读写处理接收发送和发送数据

/**
 * @author liangxuelong
 * @version 1.0
 * @description: socket 连接对象
 * 主要用于对已连接的客户端收发消息
 * @date 2023/6/19 14:43
 */
public class SocketCommunication implements ICommunication{

    private Socket socket; //已经连接的客户端对象

    private AbstractSocketServer socketServer; //来自哪个服务器,创建的服务器对象

    public SocketCommunication(@NotNull Socket socket, AbstractSocketServer socketServer) {
        this.socket = socket;
        this.socketServer = socketServer;
    }

    @Override
    public Socket getSocket() {
        return socket;
    }

    @Override
    public void handle() throws Exception {
        try {
            System.out.println(socket.getInetAddress()
                    .getHostAddress()+" 已连接");
            InputStream in = socket.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ( (len = in.read(b)) != -1) {
                output.write(b, 0, len);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                if(in.available() == 0) {
                    this.receive(socket,output.toByteArray());
                    output.reset();
                }
                b = new byte[1024];
                len = 0;
            }
        } catch (IOException ioException) {
            throw ioException;
        }
    }

    /**
     * @description: 接收数据,对客户端接收的数据进行统一处理
     * 可以编写相应的处理逻辑,我这里是服务器端收到消息后。回复当前连接数量、
     * @author liangxuelong
     * @date 2023/6/19 17:30
     * @version 1.0
     */
    @Override
    public void receive(Socket socket, byte[] data) throws Exception {
        //服务器接收客户端消息
        System.out.println(socket.getInetAddress().getHostAddress()+" 发送:"+new String(data,"gbk"));
        //服务器回复客户端消息
        String msg = "当前连接数量:"+socketServer.getConnectSize();
        socketServer.send(socket.getInetAddress().getHostAddress(),
                msg.getBytes("gbk"));
    }

    /**
     * @description: 发送数据
     * @author liangxuelong
     * @date 2023/6/19 17:30
     * @version 1.0
     */
    @Override
    public void send(byte[] data) throws Exception {
        socket.getOutputStream().write(data);
    }
    /**
     * @description: 断开连接
     * @author liangxuelong
     * @date 2023/6/19 17:30
     * @version 1.0
     */
    @Override
    public void disconnect() throws Exception {
        System.out.println(socket.getInetAddress()
                .getHostAddress()+" 已断开");
        socket.close();
    }

}

定义一个自定义异常ConnectException处理连接数超出最大限制

/**
 * @author liangxuelong
 * @version 1.0
 * @description:
 * @date 2023/6/19 16:25
 */
public class ConnectException extends Exception{
    public ConnectException(int maxSize) {
        super("连接数量超出最大限制,连接失败! 当前最大连接数:"+maxSize);
    }
}

最后定义main方法进行测试

/**
 * @author liangxuelong
 * @version 1.0
 * @description: TODO
 * @date 2023/6/19 15:57
 */
public class Main {

    public static void main(String[] args) {
        SocketServer server = new SocketServer("192.168.0.100",5032);
        server.setMaxConnectSize(2); //设置最大连接数量
        server.startServer();

        //每5秒钟获取一下当前连接,并发送数据
        new Thread(() -> {

            while (true) {
                //获取所有连接
                for (String ip : server.getConnectIpAddress()) {
                    try {
                        System.out.println("当前已连接ip:"+ip);
                        String msg = "向指定客户端发送消息: "+ip+" 你好";
                        //向指定ip发送消息
                        if (server.send(ip,msg.getBytes("gbk"))) {
                            System.out.println("向 "+ip+" 发送了 ["+msg+"]");
                        }
                        
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
        }).start();
    }
}

查看测试结果

1687517358469

小结

具体代码实现细节就不多描述了。有问题可以联系交流。文章来源地址https://www.toymoban.com/news/detail-670071.html

到了这里,关于java socket Server TCP服务端向指定客户端发送消息;可查看、断开指定连接的客户端;以及设置客户端最大可连接数量。的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Linux网络编程:socket、客户端服务器端使用socket通信(TCP)

    socket(套接字),用于网络中不同主机间进程的通信。 socket是一个伪文件,包含读缓冲区、写缓冲区。 socket必须成对出现。 socket可以建立主机进程间的通信,但需要协议(IPV4、IPV6等)、port端口、IP地址。          (1)创建流式socket套接字。                 a)此s

    2024年02月11日
    浏览(18)
  • SpringBoot搭建Netty+Socket+Tcp服务端和客户端

    yml配置:    完成,启动项目即可自动监听对应端口 这里为了测试,写了Main方法,可以参考服务端,配置启动类 ,实现跟随项目启动   ......想写就参考服务端...... 有测试的,,,但是忘记截图了................

    2024年02月15日
    浏览(23)
  • Socket实例,实现多个客户端连接同一个服务端代码&TCP网络编程 ServerSocket和Socket实现多客户端聊天

    Java socket(套接字)通常也称作\\\"套接字\\\",用于描述ip地址和端口,是一个通信链的句柄。应用程序通常通过\\\"套接字\\\"向网络发出请求或者应答网络请求。 使用socket实现多个客户端和同一客户端通讯;首先客户端连接服务端发送一条消息,服务端接收到消息后进行处理,完成后再

    2024年02月12日
    浏览(24)
  • Socket网络编程(TCP/IP)实现服务器/客户端通信。

    一.前言 回顾之前进程间通信(无名管道,有名管道,消息队列,共享内存,信号,信号量),都是在同一主机由内核来完成的通信。 那不同主机间该怎么通信呢? 可以使用Socket编程来实现。 Socket编程可以通过网络来实现实现不同主机之间的通讯。 二.Socket编程的网络模型如

    2024年02月08日
    浏览(36)
  • python网络编程:通过socket实现TCP客户端和服务端

    目录 写在开头 socket服务端(基础) socket客户端(基础) 服务端实现(可连接多个客户端)  客户端实现 数据收发效果   近期可能会用python实现一些网络安全工具,涉及到许多关于网络的知识,逃不过的就是最基本的socket。本文将介绍如何通过python自带的socket库实现TCP客户

    2024年03月21日
    浏览(22)
  • socket的使用 | TCP/IP协议下服务器与客户端之间传送数据

    谨以此篇,记录TCP编程,方便日后查阅笔记 注意:用BufferedWriter write完后,一定要flush;否则字符不会进入流中。去看源码可知:真正将字符写入的不是write(),而是flush()。 服务器端代码: 客户端代码: 运行后结果: 服务器端: 客户端: 参考资料: https://www.bilibili.com/vid

    2024年02月09日
    浏览(19)
  • Linux网络编程:Socket套接字编程(Server服务器 Client客户端)

    文章目录: 一:定义和流程分析 1.定义 2.流程分析  3.网络字节序 二:相关函数  IP地址转换函数inet_pton inet_ntop(本地字节序 网络字节序) socket函数(创建一个套接字) bind函数(给socket绑定一个服务器地址结构(IP+port)) listen函数(设置最大连接数或者说能同时进行三次握手的最

    2024年02月12日
    浏览(21)
  • Linux下基于TCP协议的Socket套接字编程(客户端&服务端)入门详解

    写在前面: 本篇博客探讨实践环境如下: 1.操作系统: Linux 2.版本(可以通过命令 cat /etc/os-release 查看版本信息):PRETTY_NAME=“CentOS Linux 7 (Core)” 编程语言:C 常常说socket 、套接字 那么socket 到底指的是什么? socket 本质上是一个抽象的概念,它是一组用于 网络通信的 API , 提供

    2024年02月01日
    浏览(18)
  • 网络编程3——TCP Socket实现的客户端服务器通信完整代码(详细注释帮你快速理解)

    本人是一个刚刚上路的IT新兵,菜鸟!分享一点自己的见解,如果有错误的地方欢迎各位大佬莅临指导,如果这篇文章可以帮助到你,劳请大家点赞转发支持一下! 今天分享的内容是TCP流套接字实现的客户端与服务器的通信,一定要理解 DatagramSocket,DatagramPacket 这两个类的作用以及方法

    2024年02月12日
    浏览(15)
  • 基于Springboot整合Socket仿微信实现群聊、私聊功能。实现客户端client,服务端server心跳维护、超时机制【一文通】

    博主介绍: ✌java资深开发工程师、Java领域优质创作者,博客之星、专注于Java技术领域和学生毕业项目实战,面试讲解跟进,高校老师/讲师/同行交流合作✌ 胡广愿景: \\\"比特星球\\\",致力于帮助底层人员找到工作, 让每个底层人员都能找到属于自己的星球。 拓展学习领域,获

    2024年02月19日
    浏览(17)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包