问题
There question about this before, the answer is no. But now, with browserify/webpack, can I just write code like I would on server and it will run in browser, or is there any restriction that would make this impossible?
回答1:
No, you cannot. Starting a server in a browser requires access to low level functionality that simply to does not exist in a browser. Browserify cannot add fundamental low-level features to the browser that it does not have that would require additional native code support in order to make work.
Browserify can only package code that is either pure Javascript or is built on top of infrastructure that already exists in the browser or can be simulated with some pure javascript built on top of the features that do exist in the browser.
So, for example, you could take a crypto hash library from node.js that is pure javascript and does not rely on any capabilities that are not present in a browser and you could browserify it (e.g. repackage it) to use it in a browser. But, you could not take a node.js package that uses low-level UDP communication because the underlying access to UDP is not present in a browser.
In general, if the node.js code does I/O or manipulates other processes or uses any module that has native code, it will likely not work with browserify (there are a few work-arounds with some file I/O).
For additional info, see:
Does Browserify have any limitations?
Browserify Compatibility
So you don't say what your actual problem is that you're trying to solve, but usually you would start an actual server somewhere and have the browser connect to that server. If you wanted one particular browser session to appear to be the "master", you could certainly make your client/server behave that way. One client could be the master (appearing to essentially be the server itself) to other clients that connected to that same server. This would all be done by how you programmed your server and how it communicated with the various clients that connect to it. Actual servers can be made to be proxies for other clients where the client gets access to server-like functionality via the proxied connection to an actual server.
来源:https://stackoverflow.com/questions/42039634/can-i-start-a-socket-io-websocket-server-in-browser