客户端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>