java 服务端tcp方式接收和推送数据到c++或者qt(亲测可用)

方式1

java 复制代码
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

public class NumberToChinese {
List<SocketChannel> socketChannelList = new CopyOnWriteArrayList();
    List<Socket> socketList = new CopyOnWriteArrayList();

    public List<SocketChannel> getSocketChannelList() {
        return socketChannelList;
    }

    public void setSocketChannelList(List<SocketChannel> socketChannelList) {
        this.socketChannelList = socketChannelList;
    }

    public List<Socket> getSocketList() {
        return socketList;
    }

    public void setSocketList(List<Socket> socketList) {
        this.socketList = socketList;
    }
public void thread3(){
        new Thread(() ->{
            try {
                while (true){
                    Thread.sleep(1000);
                    for (Socket socket : socketList){
                        if (socket==null || !socket.isConnected()){
                            continue;
                        }
                        InputStream inputStream = socket.getInputStream();
                        StringBuffer stringBuffer = new StringBuffer();
                        char[] chars = new char[1000];
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                        int read;
                        k:while ((read = bufferedReader.read(chars)) != -1){
                            for (int i = 0; i < read; i++) {
                                stringBuffer.append(chars[i]);
                            }
                            //0d0a  c或者qt传过来的结束符  结束符可以自己商量
                            if (stringBuffer.toString().endsWith("0d0a")){
                                System.out.println("读取结束");
                                break k;
                            }
                        }
                        System.out.println("读取完毕"+stringBuffer.toString());
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"thread1").start();

        new Thread(() ->{
            try {
                ServerSocket server = new ServerSocket(8088);
                Socket socket;
                while (true){
                    socket = server.accept();
                    SocketChannel channel = socket.getChannel();
                    socketList.add(socket);
                    System.out.println("建立连接成功");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"thread2").start();
    }
}

方式2 推荐

java 复制代码
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

public class NumberToChinese {

    List<SocketChannel> socketChannelList = new CopyOnWriteArrayList();
    List<Socket> socketList = new CopyOnWriteArrayList();

    public List<SocketChannel> getSocketChannelList() {
        return socketChannelList;
    }

    public void setSocketChannelList(List<SocketChannel> socketChannelList) {
        this.socketChannelList = socketChannelList;
    }

    public List<Socket> getSocketList() {
        return socketList;
    }

    public void setSocketList(List<Socket> socketList) {
        this.socketList = socketList;
    }
    public void thread2(){
        new Thread(() ->{
            try {
                while (true){
                    Thread.sleep(1000);
                    for (SocketChannel channel : socketChannelList){
                        if (channel==null || !channel.isConnected()){
                            continue;
                        }
                        StringBuffer stringBuffer = new StringBuffer();
                        ByteBuffer buffer = ByteBuffer.allocate(  256);
                        k:while (channel.read(buffer) != -1){
                            buffer.flip();//切换读写模式,冲区的界限设理为当前位置,并将当前位到设置为0
                            byte[] array = buffer.array();
                            String qqq = new String(array,"UTF-8").trim();//c接口也得加编码,不然读取过来的是乱码
                            stringBuffer.append(qqq);
                            //0d0a  c或者qt传过来的结束符  结束符可以自己商量
                            if (stringBuffer.toString().endsWith("0d0a")){
                                System.out.println("读取结束");
                                break k;
                            }
                        }
                        System.out.println("读取完毕"+stringBuffer.toString());
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"thread1").start();

        new Thread(() ->{
            try {
                ServerSocketChannel socketchannel = ServerSocketChannel.open();
                socketchannel.bind(new InetSocketAddress("ip",8088));
                socketchannel.configureBlocking(true);//false 的话,会导致 socketchannel.accept();阻塞不了
                while (true){
                    SocketChannel socketChannel = socketchannel.accept();
                    if (socketChannel == null){
                        continue;
                    }
                    socketChannelList.add(socketChannel);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"thread2").start();
    }
}

方式3

java 复制代码
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

public class NumberToChinese {
List<SocketChannel> socketChannelList = new CopyOnWriteArrayList();
    List<Socket> socketList = new CopyOnWriteArrayList();

    public List<SocketChannel> getSocketChannelList() {
        return socketChannelList;
    }

    public void setSocketChannelList(List<SocketChannel> socketChannelList) {
        this.socketChannelList = socketChannelList;
    }

    public List<Socket> getSocketList() {
        return socketList;
    }

    public void setSocketList(List<Socket> socketList) {
        this.socketList = socketList;
    }
	public void thread1(){
        new Thread(() ->{
            try {
                while (true){
                    Thread.sleep(1000);
                    for (SocketChannel channel : socketChannelList){
                        if (channel==null || !channel.isConnected()){
                            continue;
                        }
                        StringBuffer stringBuffer = new StringBuffer();
                        ByteBuffer buffer = ByteBuffer.allocate(  256);
                        k:while (channel.read(buffer) != -1){
                            buffer.flip();
                            byte[] array = buffer.array();
                            String qqq = new String(array,"UTF-8").trim();
                            stringBuffer.append(qqq);
                            buffer.flip();//切换读写模式,冲区的界限设理为当前位置,并将当前位到设置为0
                            //0d0a  c或者qt传过来的结束符
                            if (stringBuffer.toString().endsWith("0d0a") || stringBuffer.toString().endsWith("0DOA")){
                                System.out.println("读取结束");
                                break k;
                            }
                        }
                        System.out.println("读取完毕"+stringBuffer.toString());
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"thread1").start();

        new Thread(() ->{
            try {
                Selector se = Selector.open();//原则器
                ServerSocketChannel socketchannel = ServerSocketChannel.open();
                socketchannel.bind(new InetSocketAddress("ip",8088));
                socketchannel.configureBlocking(false);
                socketchannel.register(se, SelectionKey.OP_ACCEPT);
                while (true){
                    se.select();
                    Set<SelectionKey> selectionKeys = se.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isAcceptable()){
                            SocketChannel channel = socketchannel.accept();
                            socketChannelList.add(channel);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"thread2").start();
    }
}

1、自己写个接口,让c++或者qt写个动态链接库,后端调用这个接口,将ip和端口号发送给他们,这样就能建立连接了

2、java推送数据,写个接口,读取你自己添加的集合,然后循环得到自己的通道

然后

java 复制代码
public void test(){
        try {
            if (CollectionUtils.isNotEmpty(socketChannelList)){
                for (SocketChannel channel : socketChannelList) {
                    String s = new String();//你传输给网络的数据
                    ByteBuffer buffer = ByteBuffer.wrap(s.getBytes());
                    while (buffer.hasRemaining()){
                        channel.write(buffer);
                    }
                    channel.close();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
相关推荐
一叶飘零_sweeeet1 分钟前
从字节到网页:HTTP 与 TCP 的底层密码全解析
tcp/ip·http·三次握手
默默coding的程序猿4 分钟前
3.git的分支携带问题是什么?怎么解决?
java·git·python·svn·gitee·github·intellij-idea
十五年专注C++开发10 分钟前
CFF Explorer: 一款Windows PE 文件分析的好工具
c++·windows·microsoft
郝学胜-神的一滴25 分钟前
计算机图形学中的光照模型:从基础到现代技术
开发语言·c++·程序人生·图形渲染
望获linux1 小时前
【实时Linux实战系列】Linux 内核的实时组调度(Real-Time Group Scheduling)
java·linux·服务器·前端·数据库·人工智能·深度学习
Never_Satisfied1 小时前
在 JavaScript 中,删除数组中内容为xxx的元素
java·前端·javascript
MC丶科1 小时前
【SpringBoot常见报错与解决方案】端口被占用?Spring Boot 修改端口号的 3 种方法,第 3 种 90% 的人不知道!
java·linux·spring boot
怪兽20142 小时前
Redis常见性能问题和解决方案
java·数据库·redis·面试
zz-zjx2 小时前
JVM 内存结构与 GC 机制详解( 实战优化版)
java·jvm·tomcat
nvvas2 小时前
Android Studio JAVA开发按钮跳转功能
android·java·android studio