04_ok_java_websocket_端口转发_将服务器的流端口转到本地

客户端socket

bash 复制代码
package com.example.filedemo.controller;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Base64;
import java.util.Timer;
import javax.sound.sampled.*;
public class AudioWebSocketClient extends WebSocketClient {
    public AudioWebSocketClient(URI serverUri) {
        super(serverUri);
    }
    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("Connected to the server.");
    }
    @Override
    public void onMessage(String message) {
        // 处理接收到的消息
        System.out.println("Received message: " + message);
    }
    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("Disconnected from server: " + reason);
    }
    @Override
    public void onError(Exception ex) {
        ex.printStackTrace();
    }
    // 将 byte[] 转换为 Base64 编码的字符串
    public static String byteArrayToString(byte[] byteArray) {
        // 使用 Base64 编码将字节数组转换为字符串
        return Base64.getEncoder().encodeToString(byteArray);
    }
    // 从 Base64 字符串解码为 byte[]
    public static byte[] stringToByteArray(String base64String) {
        // 使用 Base64 解码字符串为字节数组
        return Base64.getDecoder().decode(base64String);
    }
    public static void main(String[] args) throws Exception {
        //URI serverUri = new URI("ws://yourserverip:9395/dotcwsasr?lanid=0&userid=1121212&token=1234567890&sid=sid1001");
        URI serverUri = new URI("ws://127.0.0.1:8888");
        AudioWebSocketClient client = new AudioWebSocketClient(serverUri);
        client.connectBlocking();
        //字符串socket请求
        //        while (true) {
        //            client.send("Hello, WebSocket server!@@@@@@@@@@@@@@@@@@@@@@@@@");
        //        }
       //声音流socket请求
//        File file = new File("D:\\work\\20241213\\3.wav");
//        AudioInputStream audioInputStream = null;
//        try {
//            audioInputStream = AudioSystem.getAudioInputStream(file);
//        } catch (UnsupportedAudioFileException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        AudioFormat format = audioInputStream.getFormat();
//        int bufferSize = 3200;
//        byte[] buffer = new byte[bufferSize];
//        int bytesRead;
//        while (true) {
//            try {
//                if (!((bytesRead = audioInputStream.read(buffer)) != -1)) {
//                    break;
//                } else {
//                    byte[] smallerBuffer = new byte[bytesRead];
//                    System.arraycopy(buffer, 0, smallerBuffer, 0, bytesRead);
//                    buffer = smallerBuffer;
//                    // String str = new String(buffer);
//                    client.send(byteArrayToString(buffer));
//                    // client.send(buffer);
//                }
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }
//        try {
//            audioInputStream.close();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        //麦克风声音socket请求
        try {
            // 设置音频格式
            AudioFormat format = new AudioFormat(16000, 16, 1, true, false);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

            // 检查是否支持
            if (!AudioSystem.isLineSupported(info)) {
                System.out.println("Line not supported");
                return;
            }

            // 打开 TargetDataLine
            TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
            line.open(format);

            // 启动采集
            line.start();

            // 创建缓冲区
            byte[] buffer = new byte[3200]; // 每次读取 3200 字节,等同于 1600 采样点(16K 采样率,16-bit 单声道)

            while (true) {
                // 读取音频数据到缓冲区
                int bytesRead = line.read(buffer, 0, buffer.length);
                if (bytesRead > 0) {
                    byte[] smallerBuffer = new byte[3200];
                    System.arraycopy(buffer, 0, smallerBuffer, 0, bytesRead);
                    buffer = smallerBuffer;
                    client.send(byteArrayToString(buffer));
                }
            }
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }
}

服务端socket

bash 复制代码
package com.example.filedemo.controller;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.server.WebSocketServer;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;

import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Base64;
public class WebSocketForwardingServer extends WebSocketServer {
    private WebSocketClient remoteWebSocket;

    // 远程 WebSocket 地址
    private String remoteWsUrl = "ws://YOURSERVERIP:9395/dotcwsasr?lanid=0&userid=123322&token=1234567890&sid=sid1001";
    public WebSocketForwardingServer(int port) {
        super(new InetSocketAddress(port));
    }
    // 将 byte[] 转换为 Base64 编码的字符串
    public static String byteArrayToString(byte[] byteArray) {
        // 使用 Base64 编码将字节数组转换为字符串
        return Base64.getEncoder().encodeToString(byteArray);
    }
    // 从 Base64 字符串解码为 byte[]
    public static byte[] stringToByteArray(String base64String) {
        // 使用 Base64 解码字符串为字节数组
        return Base64.getDecoder().decode(base64String);
    }
    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        System.out.println("Client connected: " + conn.getRemoteSocketAddress());
        // 建立连接到远程 WebSocket
        connectToRemoteWebSocket(conn);
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        System.out.println("Client disconnected: " + conn.getRemoteSocketAddress());
    }
    // 用于控制连接过程
    // 需要从远程 WebSocket 获取数据的地址
    private static final String REMOTE_WEBSOCKET_URL = "ws://yourserverip:9395/dotcwsasr?lanid=0&userid=13606060253&token=1234567890&sid=sid1001";
    @Override
    public void onMessage(WebSocket webSocket, String s) {
        remoteWebSocket.send(stringToByteArray(s));
    }
    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
    }
    @Override
    public void onStart() {
        System.out.println("onStart-------------------------- start  ");
    }
    // 连接到远程 WebSocket 服务
    private void connectToRemoteWebSocket(WebSocket clientWebSocket) {
        try {
            remoteWebSocket = new WebSocketClient(new URI(remoteWsUrl)) {
                private WebSocket[] connections;
                public WebSocket[] getConnections() {
                    return connections;
                }
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    System.out.println("Connected to remote WebSocket server");
                }
                @Override
                public void onMessage(String message) {
                    clientWebSocket.send(message);
                }
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    System.out.println("Remote WebSocket closed: " + reason);
                }
                @Override
                public void onError(Exception ex) {
                    ex.printStackTrace();
                }
            };
            remoteWebSocket.connectBlocking();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    static WebSocketForwardingServer server = new WebSocketForwardingServer(8888);
    public static void main(String[] args) {
        int port = 8888;  // 设置本地 WebSocket 服务器的端口
        server.start();
        System.out.println("Server started on port: " + port);
    }
}

POM

bash 复制代码
		<dependency>
			<groupId>org.java-websocket</groupId>
			<artifactId>Java-WebSocket</artifactId>
			<version>1.3.5</version>
		</dependency>
相关推荐
理想不理想v12 分钟前
websocket的心跳检测和断线重连
网络·websocket·网络协议
二进制诗人14 分钟前
linux中 umask 命令
linux·运维·服务器
白#泽17 分钟前
课上测试:商用密码接口实现
服务器·数据库·算法
Sthamansa28 分钟前
Java学习笔记(13)——面向对象编程
java·笔记·学习
破-风1 小时前
FTP华为设备上进行配置
java·华为·restful
fen_fen1 小时前
Docker如何运行一个Java的jar包程序
java·开发语言
坊钰1 小时前
【Java 数据结构】如何写一副扑克牌 (附:全部码源) !!!
java·开发语言·前端·数据结构·学习
代码中の快捷键1 小时前
MVCC了解
运维·服务器·数据库
代码小鑫2 小时前
【毕业设计】A079-基于Java的影院订票系统的设计与实现
java·开发语言·数据库·spring boot·后端·毕业设计·课程设计