Giter VIP home page Giter VIP logo

ws2s's Introduction

also see: https://gitee.com/apihub/ws2s

ws2s--bring socket to browser-side js

ws2s(websocket to socket) is a websocket server that handle socket(tcp)s.

the simplest workflow might be like this:

  1. a websocket client(we called "ws") ask ws2s_server to create a socket(we called "s") for it.
  2. "ws" ask ws2s_server to use "s" to send data.
  3. when "s" received data, ws2s_server will notify "ws" with the received data.

with this workflow, javaScript running on a browser got the ability to use socket.

client case

  • a ws2s server at wss://ws2s.feling.net/ is ready for test case.
  • an online redis gui client powered by ws2s is provided at https://feling.net/redis/.

use origin javaScript

var ws = new WebSocket("wss://ws2s.feling.net/")
ws.onmessage = (event) => {
    console.log("onmessage: ", event.data)
}
ws.onopen = () => {
    console.log("onopen")
    ws.send(JSON.stringify(
        {
            command: "connect",
            host: "feling.net",
            port: 80
        }
    ))
    ws.send(JSON.stringify(
        {
            command: "send",
            data: "GET / HTTP/1.1\r\nHost: feling.net\r\nConnection: close\r\n\r\n"
        }
    ))
}
ws.onclose = () => {
    console.log("onclose")
}
var socket = new WS2S("wss://ws2s.feling.net/").newSocket()

$('#connect-button').bind("click", () => {
    socket.connect("feling.net", 80)
})

$('#send-button').bind("click",  () => {
    socket.send("GET / HTTP/1.1\r\nHost: feling.net\r\nConnection: close\r\n\r\n")
})

socket.onRecv = (data) => {
    console.log('onRecv', data)
}

install

ws2s works with py2、py3 on Linux、OSX. Windows users please try Windows Subsystem for Linux(WSL).

It is recommended to install from github:

pip install git+https://github.com/playay/ws2s --upgrade

you can also install ws2s from pypi:

pip install ws2s-python --upgrade

after installed ws2s:
ws2sd command can be used in shell,
~/.ws2s/ directory will be created when you exec ws2sd

config

config file is store at ~/.ws2s/config.json. modify it then exec ws2sd restart

start on boot

at see this wiki

protocol

request

here are some examples of requests:

{
    "command": "connect",
    "host":"127.0.0.1",
    "port":80
}
{
    "command": "send",
    "data":"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"
}

you can find out that:

  1. message(we called request) send to ws2s_sever is a json format string.
  2. a command field is required. other fields are dependent on different commands
  3. this wiki describes details of each command.

response

message(we called response) received from ws2s_sever, is a json format string too:

{
    "success": true,
    "code": -1,
    "message": "recv data",
    "data": "JDINCk9LDQo="
}
As the example above:    
- "message" field is for human.   
- "success" field can be ignored.     

when "code" field = -1, "data" field is presented.     
    that means ws2s_server received data from peer. "data" is a base64 string representing a byte array.     

when "code" field = 0.      
    usually means ws2s_server successfully completed the most recent command    

when "code" field > 0.      
    means something is not normal:      
    when "code" = 1:    
        unknown exception, you can submit an issue to ws2s    

    when "code" = 2:    
        ConnectionRefusedError raisesd when ws2s_server try to   
        connect host:port you specified    

    when "code" = 3:    
        IllegalSocketState, just reSend an "connect" request like:    
        {"command":"connect","host":"127.0.0.1","port":80}    

    when "code" = 4:    
        usually means you want ws2s_server to connect 127.0.0.1, but ws2s_server refused     
        to do that. this feature is configurable in `~/.ws2s/config.json`    
    
    when "code" = 5:    
        socket connection closed by socket server you connected to    

    when "code" = 6:    
        failed to open ssh tunnel    

dev

pipenv shell





python setup.py bdist_wheel
python setup.py sdist
twine upload  dist/*

ws2s's People

Contributors

playay avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ws2s's Issues

binary protocol

Would have been nice with a binary protocol instead of base64
base64 adds a 1/3 extra bandwidth, and it is wasteful to have to decode and encode stuff and include a base64 encoder/deocder to do so.

const ws = new WebSocket(...)
ws.binaryType = "arraybuffer";

so JSON don't fit in well when you want to send binary data. and retrieving json with binary data don't make the communication any better

  • have the first byte or something be the data.code or something
  • have the first 2-x bytes indicate how long your (possible json) message is and the rest of the binary is the actual "data.data" (aka binary payload)

and with a binary protocol then i don't mean some BSON, protobuf or any other serialization that you would need a library for IMO,
should be dependent free and easy to parse with vanilla javascript (DataView comes to mind if you need something more fancy)

TextEncoder & TextDecoder, is easy to use if you have to convert to/from string & buffer

obfuscated javascript?

Any particular reason why the first line of the .js library code is obfuscated? Look really sus tbh.
(function(r){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=r()}else if(typeof define==="function"&&define.amd){define([],r)}else{var e;if(typeof window!=="undefined"){e=window}else if(typeof global!=="undefined"){e=global}else if(typeof self!=="undefined"){e=self}else{e=this}e.WS2SBase64=r()}})(function(){var r,e,n;return function(){function r(e,n,t){function o(i,a){if(!n[i]){if(!e[i]){var u=typeof require=="function"&&require;if(!a&&u)return u(i,!0);if(f)return f(i,!0);var d=new Error("Cannot find module '"+i+"'");throw d.code="MODULE_NOT_FOUND",d}var c=n[i]={exports:{}};e[i][0].call(c.exports,function(r){var n=e[i][1][r];return o(n?n:r)},c,c.exports,r,e,n,t)}return n[i].exports}var f=typeof require=="function"&&require;for(var i=0;i<t.length;i++)o(t[i]);return o}return r}()({"/":[function(r,e,n){"use strict";n.byteLength=c;n.toByteArray=v;n.fromByteArray=s;var t=[];var o=[];var f=typeof Uint8Array!=="undefined"?Uint8Array:Array;var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var a=0,u=i.length;a<u;++a){t[a]=i[a];o[i.charCodeAt(a)]=a}o["-".charCodeAt(0)]=62;o["_".charCodeAt(0)]=63;function d(r){var e=r.length;if(e%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}return r[e-2]==="="?2:r[e-1]==="="?1:0}function c(r){return r.length*3/4-d(r)}function v(r){var e,n,t,i,a;var u=r.length;i=d(r);a=new f(u*3/4-i);n=i>0?u-4:u;var c=0;for(e=0;e<n;e+=4){t=o[r.charCodeAt(e)]<<18|o[r.charCodeAt(e+1)]<<12|o[r.charCodeAt(e+2)]<<6|o[r.charCodeAt(e+3)];a[c++]=t>>16&255;a[c++]=t>>8&255;a[c++]=t&255}if(i===2){t=o[r.charCodeAt(e)]<<2|o[r.charCodeAt(e+1)]>>4;a[c++]=t&255}else if(i===1){t=o[r.charCodeAt(e)]<<10|o[r.charCodeAt(e+1)]<<4|o[r.charCodeAt(e+2)]>>2;a[c++]=t>>8&255;a[c++]=t&255}return a}function l(r){return t[r>>18&63]+t[r>>12&63]+t[r>>6&63]+t[r&63]}function h(r,e,n){var t;var o=[];for(var f=e;f<n;f+=3){t=(r[f]<<16&16711680)+(r[f+1]<<8&65280)+(r[f+2]&255);o.push(l(t))}return o.join("")}function s(r){var e;var n=r.length;var o=n%3;var f="";var i=[];var a=16383;for(var u=0,d=n-o;u<d;u+=a){i.push(h(r,u,u+a>d?d:u+a))}if(o===1){e=r[n-1];f+=t[e>>2];f+=t[e<<4&63];f+="=="}else if(o===2){e=(r[n-2]<<8)+r[n-1];f+=t[e>>10];f+=t[e>>4&63];f+=t[e<<2&63];f+="="}i.push(f);return i.join("")}},{}]},{},[])("/")});

Error when sending large files

I was trying to send a large file (about 302KB in base64 format using "sendb" command ) to the ws2s server.It gave me following error:

Exception happened during processing of request from ('127.0.0.1', 54231)
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 599, in process_request_thread
    self.finish_request(request, client_address)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/Library/Python/2.7/site-packages/ws2s/websocket_server.py", line 162, in __init__
    StreamRequestHandler.__init__(self, socket, addr, server)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 655, in __init__
    self.handle()
  File "/Library/Python/2.7/site-packages/ws2s/websocket_server.py", line 175, in handle
    self.read_next_message()
  File "/Library/Python/2.7/site-packages/ws2s/websocket_server.py", line 235, in read_next_message
    opcode_handler(self, message_bytes.decode('utf8'))
  File "/Library/Python/2.7/site-packages/ws2s/websocket_server.py", line 121, in _message_received_
    self.message_received(self.handler_to_client(handler), self, msg)
  File "/Library/Python/2.7/site-packages/ws2s/ws2s_server.py", line 37, in message_received_wrapper
    if response_message:
UnboundLocalError: local variable 'response_message' referenced before assignment

Small files works fine. Any help?

Accept unmasked connections

Hi,
is there a way that I can make ws2s skip the mask verification and accept unmasked connection? I ran into some trouble with a library. It has a "bug", it doesn't mask the payload and the connection is refused every time I try to connect. Until this bug is fixed, I need a way to test my program. Can I tell ws2s to accept unmasked connections? Thanks!

file location?

(all files are store in ~/.ws2s/)
where the hell is ~/.ws2s/ ??? I can not find this directory to edit the config file. I am using windows 11 OS

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.