1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ws:WebSocketServerはBlobで受ける

Last updated at Posted at 2022-01-22

「ws node.js」で検索して出てくるサンプルコードがどれも送信内容次第で失敗する。
テキストからBlobに変えたらうまく行った。根本的原因は不明だがとりあえず。

追記:iPhone Safari で static 使っちゃ駄目らしい。なんでだよ

nodeApp.js
const WebSocketServer = require("ws").Server
const server = new WebSocketServer({ port: 5001 })
server.on("connection", client => {
	client.on('message', message => {
		server.clients.forEach(v => {
			if(v !== client) v.send(message)
		})
	})
	console.log('_connections',server._server._connections)
})
plainWeb.js
$(e=>{
	var m = new Messenger.Nodejs().message(e=>{
		console.log(e)
	}).open()
	$('body').append(
		$('<button>').append('test').click(e=>{
			m.send({type:'text',value:'サンプルコードがどうも送信内容次第で失敗する。サンプルコードがどうも送信内容次第で失敗する。'})
		})
	)
})

var Messenger = {}
Messenger.Socket = class{
	constructor(){
		this.hook = {
			message	: e=>{},
			error	: e=>console.log(e),
			status	: e=>console.log(e),
		}
	}
	open(){}
	message(f){	this.hook.message	= f; return this}
	error(f){	this.hook.error		= f; return this}
	status(f){	this.hook.status	= f; return this}
	get connecting(){
		if(this.socket==null) return false
		return this.socket.readyState==WebSocket.OPEN
	}
	send(e){
		if(this.connecting){
			this.socket.send(JSON.stringify(e))
		}else{
			this.hook.error(e)
		}
		return this
	}
}
Messenger.Nodejs = class extends Messenger.Socket{
	static url = 'ws://192.168.10.3:5001/'
	open(url){
		if(this.connecting) return this
		try{
			var s = new WebSocket(url||this.constructor.url);
		}catch(error){
			console.log(error)
			this.hook.error(error)
		}
		if(s){
			var r = new FileReader();
			r.onload	= e=>this.hook.message(JSON.parse(r.result))
			s.onmessage	= e=>{
				if(e.data instanceof Blob){
			        r.readAsText(e.data);//BlobをFileReaderで読む
			    }else{
			    	this.hook.message(JSON.parse(e.data))
			    }
			}
			//s.onmessage	= e=>this.hook.message(JSON.parse(e.data))
			s.onerror	= e=>this.hook.error(e)
			s.onopen	= e=>this.hook.status(e)
			s.onclose	= e=>this.hook.status(e)
			this.socket = s
		}
		return this
	}
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?