问题描述
我正在研究websocket并且已经使用websocket / json完成了聊天程序。但我坚持上传ATM的文件。任何建议&回答会很感激。
I'm studying websocket and have done chat program with websocket/json. But I'm stuck at file uploading ATM. Any advice & answer would be thankful.
服务器端:
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>
服务器端关闭原因消息如下
server side closed reason message is as below
套接字已关闭:已解码的文本消息对于输出缓冲区而言太大而且端点不支持部分消息
Q1:似乎它是根据封闭原因找到文本处理方法而不是二进制处理方法,我该如何解决这个问题?
Q1: It seems that it is finding text processing method instead of binary processing method according to the closed reason, how can I fix this?
Q2:我应该将数据类型更改为Blob以进行传输在javascript端文件?那怎么样?
Q2: Should I change data type to Blob to transfer file on javascript side? Then how?
额外问:可以有人链接websocket文件传输的示例源(java websocket或javascript这两个)吗?
extra Q: May anyone link example source(es) of websocket file transferring(java websocket or javascript either/both)?
感谢阅读:)
推荐答案
经过一番研究和尝试,我发现'reader.readAsBinaryString(file);'是问题1的原因。将其更改为'reader.readAsArrayBuffer(file);'我的第一个问题已经解决。
After some researches and tries, I found out that 'reader.readAsBinaryString(file);' was a cause of Question 1. Changing it into 'reader.readAsArrayBuffer(file);' my first problem has been solved.
另外,由于websocket会自动将文件作为多个部分数据传输,因此我更改了源代码,如下所示。 只有当文件大小不那么大时,才有效。 :/
In addition, since websocket transfers a file as several partial data automatically, I changed source as below. This works! only when the file size is not so big. :/
更改服务器端来源:
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 {
static File uploadedFile = null;
static String fileName = null;
static FileOutputStream fos = null;
final static String filePath="d:/download/";
@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 Data");
while(msg.hasRemaining()) {
try {
fos.write(msg.get());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnMessage
public void message(Session session, String msg) {
System.out.println("got msg: " + msg);
if(!msg.equals("end")) {
fileName=msg.substring(msg.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();
}
}
}
@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];
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>
</body>
</html>
我仍然无法弄清如何传输更大尺寸的文件。 (我怀疑自动超时和/或缓冲区大小)。有什么建议吗?
Still I cannot figure out how to transfer larger size file. (I'm suspecting auto-timeout and/or buffer size). Any advice plz?
这篇关于使用java websocket API和Javascript上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!