我正在学习websocket,并且已经用websocket / json制作了聊天程序。但是我当前遇到了文件上传问题,需要一些建议和答案。非常感谢!
服务器端:
package websocket;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/receive/fileserver")
public class FileServer {
@OnOpen
public void open(Session session, EndpointConfig conf) {
System.out.println("chat ws server open");
}
@OnMessage
public void processUpload(ByteBuffer msg, boolean last, Session session) {
System.out.println("Binary message");
FileOutputStream fos = null;
File file = new File("D:/download/tmp.txt");
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte readdata = (byte) -999;
while(readdata!=-1) {
readdata=msg.get();
try {
fos.write(readdata);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnMessage
public void message(Session session, String msg) {
System.out.println("got msg: " + msg + msg.length());
}
@OnClose
public void close(Session session, CloseReason reason) {
System.out.println("socket closed: "+ reason.getReasonPhrase());
}
@OnError
public void error(Session session, Throwable t) {
t.printStackTrace();
}
}
客户端:
<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:8080/MyHomePage/receive/fileserver");
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];
var reader = new FileReader();
var rawData = new ArrayBuffer();
reader.loadend = function() {
}
reader.onload = function(e) {
rawData = e.target.result;
ws.send(rawData);
alert("the File has been transferred.")
}
reader.readAsBinaryString(file);
}
</script>
</body>
</html>
服务器端关闭原因消息如下:
socket关闭:解码的文本消息对于输出缓冲区来说太大了,并且终端点不支持部分消息
Q1:根据关闭原因,似乎是正在寻找文本处理方法而非二进制处理方法,我该如何解决?
Q2:我应该将数据类型更改为Blob以在JavaScript端传输文件吗?那怎么做?
额外问题:能否提供Websocket文件传输的示例源代码(Java Websocket或JavaScript)?
谢谢阅读 :)