我有一个 websocket 客户端代码,当我通过它上传文件时,web socket 服务器会接收该文件。但大小始终为零。我正在使用来自tootallnate 的Java-Websocket 服务器。下面是我的客户端代码。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Chat</title>
<script type="text/javascript" src="/MyHomePage/jquery-2.0.3.min.js"> </script>
</head>
<body>
<h2>File Upload</h2>
Select file
<input type="file" id="filename" />
<br>
<input type="button" value="Connect" onclick="connectChatServer()" />
<br>
<input type="button" value="Upload" onclick="sendFile()" />
<script>
var ws;
function connectChatServer() {
ws = new WebSocket(
"ws://localhost:8887/");
ws.binaryType = "arraybuffer";
ws.onopen = function() {
alert("Connected.")
};
ws.onmessage = function(evt) {
alert(evt.msg);
};
ws.onclose = function() {
alert("Connection is closed...");
};
ws.onerror = function(e) {
alert(e.msg);
}
}
function sendFile() {
var file = document.getElementById('filename').files[0];
ws.send('filename:'+file.name);
var reader = new FileReader();
var rawData = new ArrayBuffer();
//alert(file.name);
reader.loadend = function() {
}
reader.onload = function(e) {
rawData = e.target.result;
ws.send(rawData);
alert("the File has been transferred.")
ws.send('end');
}
reader.readAsArrayBuffer(file);
}
</script>
下面是我的网络套接字服务器代码。
@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("received message from " + conn.getRemoteSocketAddress() + ": " + message);
if (!message.equals("end")) {
fileName = message.substring(message.indexOf(':') + 1);
uploadedFile = new File(filePath + fileName);
try {
fos = new FileOutputStream(uploadedFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onMessage(WebSocket conn, ByteBuffer message) {
System.out.println("Binary Data");
while (message.hasRemaining()) {
try {
fos.write(message.get());
} catch (IOException e) {
e.printStackTrace();
}
}
}
请指教。