View Single Post
Peace-Maker
SourceMod Plugin Approver
Join Date: Aug 2008
Location: Germany
Old 04-11-2012 , 19:33   Re: [DEV] WebSocket Server
Reply With Quote #2

Example

Simple Webchat
HTML based off phpwebsocket's client.html

Creating a connection and listening for events in javascript.
Replace the ip and port with the ones you're using in your websocket_test.sp.
PHP Code:
var socket;

function 
init(){
  
  var 
host "ws://192.168.1.100:12345/";
  try{
    if(!
window.WebSocket)
        
socket = new MozWebSocket(host);
    else
        
socket = new WebSocket(host);
    
log('WebSocket - status '+socket.readyState);
    
socket.onopen    = function(msg){ log("Welcome - status "+this.readyState); };
    
socket.onmessage = function(msg){ log("Received: "+msg.data); };
    
socket.onerror = function(msg){ log("Error!"); };
    
socket.onping = function(msg){ log("Received ping: "+msg.data); };
    
socket.onpong = function(msg){ log("Received pong: "+msg.data); };
    
socket.onclose   = function(msg){ log("Disconnected - status "+this.readyState+" Code: "+msg.code+". Reason:"+msg.reason+" - wasClean: "+msg.wasClean); };
  }
  catch(
ex){ log('Error: '+ex); }
  $(
"msg").focus();

The websocket_test.sp plugin just creates a websocket on port 12345 and listenes for new connections. If some client sends anything to the server, it relays it to all other connected clients as well as to the game chat. Simple as that ;)

You need to strip the .txt suffix off the client.html. The forum won't let me upload .html files.

SourceTV2D
This is the reason why this plugin was made initially. It's still not finished at all and i'm no javascript pro, so the code isn't easy to read, but it works to some extend.
You could preview what's possible with WebSockets over at http://sourcetv2d.wcfan.de/ . It's a realtime stream off our deathmatch server.

Be warned, this isn't stable at all and you should only mess with it for testing and improving reasons. Please post any additions you do
You have to edit the index.html in order to set the right IP of your gameserver to connect to.
Attached Files
File Type: txt client.html.txt (2.1 KB, 895 views)
File Type: zip sourcetv2d.zip (561.5 KB, 994 views)
File Type: sp Get Plugin or Get Source (websocket_sourcetv2d.sp - 820 views - 20.3 KB)
File Type: sp Get Plugin or Get Source (websocket_test.sp - 1230 views - 3.6 KB)
__________________

Last edited by Peace-Maker; 01-12-2017 at 22:02. Reason: Updated examples with callback changes of version 1.1
Peace-Maker is offline