As you're working on a game, you might want to send JSON objects over websockets. I've tried using them and it works. You should use JSON.stringify( JSONObject ) from the server-side and JSON.parse( incomingString ) on the receiver side ( i.e. Socket ).
You can do anything with sockets. They're quite reliable. Do let us know how you progress.
Regards,
Sankarshan
var name=null;
function OnStart() {
lay = app.CreateLayout( "linear", "FillXY,HCenter" );
layChat = app.CreateScroller( 1,0.9 );
layChat.SetBackColor( "blue" );
chat= app.CreateLayout( "Linear", "FillXY" );
layChat.AddChild( chat );
lay.AddChild( layChat );
// skt= app.CreateWebSocket( "111","222","1" );
laySend= app.CreateLayout( "Linear", "Horizontal" );
msg= app.CreateTextEdit( "",0.8,0.07 );
msg.SetHint( "message" );
laySend.AddChild( msg );
btnSend= app.CreateButton( "[fa-send]", null,null, "fontawesome" );
btnSend.SetOnTouch( send );
laySend.AddChild( btnSend );
lay.AddChild( laySend );
app.AddLayout( lay );
ip = app.GetIPAddress();
if( ip == "0.0.0.0" ) {
app.ShowPopup( "Please Enable Wi-Fi" );
app.Exit();
}
app.PreventWifiSleep();
while ( name=="null" || name.indexOf(" ")>-1 ) name= prompt( "type in your name:","name" )
}
function send() {
app.HideKeyboard();
txt= app.CreateText( "["+name+"] : "+msg.GetText(),1,null,"left" );
msg.SetText( "" );
txt.SetTextSize( 15 );
txt.SetTextColor( "green" );
if ( txt != "") {
//send txt.GetText()
chat.AddChild( txt );
}
OnReceive()
}
function OnReceive()
{
txt= app.CreateText( "nomsg" /*get msg*/, 1,null, "left");
txt.SetTextSize( 15 );
txt.SetTextColor( "grey" );
chat.AddChild( txt );
}
//This WiFi messaging sample broadcasts UDP network//messages to every device inside your WiFi network (that//is running this sample). This sample could easily be//extended to create a WiFi-Chat Application or used as//starting point for a multi-player Wifi game.//(Note: A few routers block fast UDP messages by default)
//Called when application is started.function OnStart(){ //Create a layout with objects vertically centered. lay = app.CreateLayout( "linear", "VCenter,FillXY" );
txt_label = app.CreateText( "Chatbox" ); lay.AddChild( txt_label );
txt_chat = app.CreateText( "", 0.5, 0.6, "MultiLine" ); lay.AddChild( txt_chat ); txt_msg = app.CreateTextEdit( "", 0.5, 0.1, "Autoselect,Center,SingleLine" ); lay.AddChild( txt_msg );
//Create a button. btn = app.CreateButton( "Send", 0.3, 0.1 ); btn.SetMargins( 0, 0.05, 0, 0 ); lay.AddChild( btn ); btn.SetOnTouch( btn_OnTouch );
//Add layout to app. app.AddLayout( lay ); //Create UDP network object. net = app.CreateNetClient( "UDP" ); //Get the UDP broadcast address and set our port number. address = net.GetBroadcastAddress(); port = 19700; //Get our MAC address (to serve as a device id). mac = app.GetMacAddress(); //Start timer to check for incoming messages. setInterval( CheckForMsg, 200 );}
//Called when user touches our button.function btn_OnTouch(){ //Broadcast our Datagram (UDP) packet. var msg = txt_msg.GetText(); if(msg != "") { var packet = mac + "|" + mac + ": " + msg; net.SendDatagram( packet, "UTF-8", address, port ); txt_msg.SetText( "" ); } else { app.ShowPopup( "no message", "Short" ); }}
//Called by our interval timer.function CheckForMsg(){ //Try to read a packet for 1 millisec. var packet = net.ReceiveDatagram( "UTF-8", port, 1 ); if( packet ) { //Extract original parts. parts = packet.split("|"); var id = parts[0]; var msg = parts[1]; //Show the message if not sent by this device. if( id != mac ) app.ShowPopup( msg); s = txt_chat.GetText(); txt_chat.SetText( s + "\n" + msg ); }}
Heres my chat sample:
var name=null;
function OnStart() {
lay = app.CreateLayout( "linear", "FillXY,HCenter" );
layChat = app.CreateScroller( 1,0.9 );
layChat.SetBackColor( "blue" );
chat= app.CreateLayout( "Linear", "FillXY" );
layChat.AddChild( chat );
lay.AddChild( layChat );
laySend= app.CreateLayout( "Linear", "Horizontal" );
msg= app.CreateTextEdit( "",0.8,0.07 );
msg.SetHint( "message" );
laySend.AddChild( msg );
btnSend= app.CreateButton( "[fa-send]", null,null, "fontawesome" );
btnSend.SetOnTouch( send );
laySend.AddChild( btnSend );
lay.AddChild( laySend );
app.AddLayout( lay );
ip = app.GetIPAddress();
if( ip == "0.0.0.0" ) {
app.ShowPopup( "Please Enable Wi-Fi" );
app.Exit();
}
net = app.CreateNetClient( "UDP" );
address = net.GetBroadcastAddress();
port = 19700;
mac = app.GetMacAddress();
setInterval( CheckForMsg );
while ( name=="null" || name.indexOf(" ")>-1 ) name= prompt( "type in your name:","" )
}
function send() {
app.HideKeyboard();
txt= app.CreateText( "["+name+"] : "+msg.GetText(),1,null,"left" );
msg.SetText( "" );
txt.SetTextSize( 15 );
txt.SetTextColor( "green" );
if ( txt != "" ) {
net.SendDatagram( mac+"|"+txt.GetText(), "UTF-8", address, port );
chat.AddChild( txt );
}
}
function CheckForMsg() {
var text = net.ReceiveDatagram( "UTF-8", port, 1 );
if( text && text.split("|")[0] != mac ) {
txt= app.CreateText( text, 1,null, "left");
txt.SetTextSize( 15 );
txt.SetTextColor( "white" );
chat.AddChild( txt );
}
}
https://www.dropbox.com/sh/n58tatyud37lfla/AAAhrB7fwfjbzyaIAkefnkrta?dl=0
I think you must be connected with the same netwirk to use this right? Is it possible to send in all networks?
var status
dlg=false;
//Called when application is started.
function OnStart()
{
if (dlg) dlg.Hide();
//check iWiFi is enabled
if( app.GetIPAddress() == "0.0.0.0" ) { retry(); return }
//Create a layout with objects vertically centered.
lay=app.CreateLayout("linear","FillXY");
//create dailog
dlg=app.CreateDialog("","NoTitle,NoCancel");
layDlg=app.CreateLayout("Linear","FillXY");
layClient= app.CreateLayout( "Linear", "Horizontal" );
//create text edit to enter the key
edtKey= app.CreateTextEdit( "", 0.5, null, "singleline");
layClient.AddChild( edtKey );
//create button to prepare the client
btnClient= app.CreateButton( "Client" );
btnClient.SetOnTouch( getInput );
layClient.AddChild( btnClient );
layDlg.AddChild( layClient );
layHost= app.CreateLayout( "Linear", "Horizontal" );
//create text shows the key to give it the clients
txtKey= app.CreateText( app.GetIPAddress()+":0808", 0.5);
txtKey.SetTextSize(20)
layHost.AddChild( txtKey );
//create button to prepare the host
btnHost= app.CreateButton( "Host" );
btnHost.SetOnTouch( getInput );
layHost.AddChild( btnHost );
layDlg.AddChild( layHost );
//create button to exit the app
btnExit= app.CreateButton( "exit" );
btnExit.SetOnTouch( getInput );
btnExit.SetMargins( 0.2 );
layDlg.AddChild( btnExit );
dlg.AddLayout(layDlg);
dlg.Show();
//create scroller to scroll the chat
scroll=app.CreateScroller(1,0.9);
layScroll=app.CreateLayout("Linear");
//create the chat
chat=app.CreateText("",1,1,"MultiLine,Log");
chat.SetTextColor("black");
chat.SetBackColor("white");
chat.SetTextSize(20);
layScroll.AddChild(chat);
scroll.AddChild(layScroll);
lay.AddChild(scroll);
//layout for sending stuff
layMsg=app.CreateLayout("Linear","FillXY,Horizontal");
layMsg.SetBackColor("grey");
//create message edit
edtMsg=app.CreateTextEdit("",0.8,0.07,"MultiLine")
layMsg.AddChild(edtMsg);
//create 'send' buttom
btnSend=app.CreateButton("[fa-share]",null,0.07,"FontAwesome");
btnSend.SetTextColor("#000000");
btnSend.SetOnTouch(SendMessage);
layMsg.AddChild(btnSend);
lay.AddChild(layMsg);
//Add layout to app.
app.AddLayout(lay);
}
function getInput()
{
status= this.GetText();
if (status == "exit") app.Exit()
dlg.Hide();
if (status== "host") {
//create local server
serv=app.CreateWebServer("8080");
serv.SetFolder("/sdcard/DroidScript/DSChat");
serv.SetOnReceive(ServerOnReceive);
serv.Start();
}
if (status == "client") {
//check and exit if the device doesn't support web sockets
if(!window.WebSocket) {
alert("This device doesn't support web sockets.");
app.Exit();
}
//create the web socket
key= edtKey.GetText();
socket=new WebSocket("ws://"+key);
socket.onopen=OnSocketOpen;
socket.onmessage=OnSocketMessage;
socket.onerror=OnSocketError;
}
}
//tells the user when succesfully connected
function OnSocketOpen() {
app.ShowPopup("Connnected.","Short");
dlg.Hide();
}
//write received message from clients
function ServerOnReceive(msg,ip) { chat.Log(msg) }
//write received message
function OnSocketMessage(msg) { chat.Log(msg.data) }
//shows the error if this is the case
function OnSocketError(e) { alert("SocketError:"+e.data) }
function SendMessage() {
//get message
msg=edtMsg.GetText();
app.HideKeyboard();
edtMsg.SetText("");
//check last message for match or empty
hist= chat.GetText().split("\n");
if(msg!="" && hist[hist.length-2] != msg) {
//send message
if(status=="host")serv.SendText(msg);
if(status=="Client")socket.send(msg);
//add message to users chat
chat.Log(msg);
}
}
function retry() {
dlg= app.CreateDialog( "Please Enable Wi-Fi", "NoCancel");
laydlg= app.CreateLayout( "Linear", "Horizontal" );
//create retry button
btnRetry= app.CreateButton( "retry", 0.5,0.08, "gray")
btnRetry.SetOnTouch( OnStart );
laydlg.AddChild( btnRetry );
//create exit button
btnExit= app.CreateButton( "exit", 0.2,0.08, "gray")
btnExit.SetOnTouch( getInput );
laydlg.AddChild( btnExit );
laydlg.AddChild( btnRetry );
dlg.AddLayout( laydlg );
dlg.Show();
}
var statusdlg=false;
//Called when application is started.function OnStart(){ if (dlg) dlg.Hide(); //check iWiFi is enabled if( app.GetIPAddress() == "0.0.0.0" ) { retry(); return }
//Create a layout with objects vertically centered. lay=app.CreateLayout("Linear","FillXY"); //create dailog dlg=app.CreateDialog("","NoTitle,NoCancel"); layDlg=app.CreateLayout("Linear","FillXY"); //create text edit to enter the key txtKey= app.CreateText( "no hosts in range", 0.4, null, "Multiline" ); layDlg.AddChild( txtKey ); //create button to prepare the client btnClient= app.CreateButton( "client" ); btnClient.SetOnTouch( getInput ); layDlg.AddChild( btnClient );
//create button to prepare the host btnHost= app.CreateButton( "host" ); btnHost.SetOnTouch( getInput ); layDlg.AddChild( btnHost );
//create button to exit the app btnExit= app.CreateButton( "exit" ); btnExit.SetOnTouch( getInput ); //Create UDP network object for broadcasting our host id. net = app.CreateNetClient( "UDP" ); //Get the UDP broadcast address and set our port number. address = net.GetBroadcastAddress(); port = 19700; //Get our MAC address (to serve as a device id). mac = app.GetMacAddress(); //Start timer to check for incoming host ids. setInterval( CheckForHosts, 1000 ); //Start timer to send our host id continually if we are host. setInterval( SendHostId, 1000 );}
function getInput(){ status= this.GetText(); if (status == "exit") app.Exit() dlg.Hide(); if (status== "host") { key= txtKey.GetText(); if( key == "no hosts in range" ) { //create local server serv=app.CreateWebServer("8080"); serv.SetFolder("/sdcard/DroidScript/DSChat"); serv.SetOnReceive(ServerOnReceive); serv.Start(); } else { app.Alert( "There is already a host in range. Press client Button to connect." ); dlg.Show(); } } if (status == "client") { //check and exit if the device doesn't support web sockets if(!window.WebSocket) { alert("This device doesn't support web sockets."); app.Exit(); } //create the web socket key= txtKey.GetText(); if( key != "no hosts in range" ) { socket=new WebSocket("ws://"+key); socket.onopen=OnSocketOpen; socket.onmessage=OnSocketMessage; socket.onerror=OnSocketError; } else app.Alert( "No Hosts found in Range. Serv as host and press host Button." ); dlg.Show(); }}
//tells the user when succesfully connectedfunction OnSocketOpen() { app.ShowPopup("Connnected.","Short"); dlg.Hide();}
//write received message from clientsfunction ServerOnReceive(msg,ip) { chat.Log(msg) }
//write received messagefunction OnSocketMessage(msg) { chat.Log(msg.data) }
//shows the error if this is the casefunction OnSocketError(e) { alert("SocketError:"+e.data) }
function SendMessage() {
//get message msg=edtMsg.GetText(); app.HideKeyboard(); edtMsg.SetText("");
//check last message for match or empty hist= chat.GetText().split("\n"); if(msg!="" && hist[hist.length-2] != msg) {
//send message if(status=="host")serv.SendText(msg); if(status=="client")socket.send(msg);
//add message to users chat chat.Log(msg); }}
function retry() { dlg= app.CreateDialog( "Please Enable Wi-Fi", "NoCancel"); laydlg= app.CreateLayout( "Linear", "Horizontal" ); //create retry button btnRetry= app.CreateButton( "retry", 0.5,0.08, "gray") btnRetry.SetOnTouch( OnStart ); laydlg.AddChild( btnRetry ); //create exit button btnExit= app.CreateButton( "exit", 0.2,0.08, "gray") btnExit.SetOnTouch( getInput ); laydlg.AddChild( btnExit ); laydlg.AddChild( btnRetry ); dlg.AddLayout( laydlg ); dlg.Show();}
//Called by our interval timer.function CheckForHosts(){ //Try to read a packet for 1 millisec. var packet = net.ReceiveDatagram( "UTF-8", port, 1 ); if( packet ) { //Extract original parts. parts = packet.split("|"); var id = parts[0]; var msg = parts[1]; //Show the broadcasted host id from other devices ( if not sent by this device ). if( id != mac ) txtKey.SetText( msg ); }}
//Called by our interval timer. Broadcast our key to other devices if we are host.function SendHostId(){ //Broadcast our Datagram (UDP) packet but only if we are host. if(status=="host") { var msg = app.GetIPAddress()+":8080" if(msg != "") { var packet = mac + "|" + msg; net.SendDatagram( packet, "UTF-8", address, port ); } else { app.ShowPopup( "No ip / port, check connection.", "Short" ); } }}var status;
dlg=false;
searchHost= setInterval( CheckForHosts, 1000 );
}
function getInput()
{
status= this.GetText();
if (status == "exit") app.Exit()
dlg.Hide();
clearInterval( searchHost );
if (status== "host") {
key= txtKey.GetText();
if( key == "no hosts in range" )
{
//create local server
serv=app.CreateWebServer("8080");
serv.SetFolder("/sdcard/DroidScript/DSChat");
serv.SetOnReceive(ServerOnReceive);
serv.Start();
//Start timer to send our host id continually if we are host.
sendHost= setInterval( SendHostId, 1000 );
function SendMessage() {
//Show the broadcasted host id
if( packet ) txtKey.SetText( packet);
}
//Called by our interval timer. Broadcast our key to other devices if we are host.
function SendHostId()
{
var msg = app.GetIPAddress()
if(msg != "0.0.0.0") {
var packet = mac + "|" + msg+":0808";
net.SendDatagram( packet, "UTF-8", address, port );
}
else {
app.ShowPopup( "No ip / port, check connection.", "Short" );
//clears sendHost interval to avoid multiple shown retry dlg
clearInterval( sendHost );
retry();
}
}
You write the wrong port every time (0808 is wrong). Just a hint.
I would not clear the "send host" interval... so another device can join. But using it in the getInput-function sounds good.
I agree with the "check for host"-interval, that interval could end after clicking the client-button.
I do not know why you put the complete packet content in the txtKey... with your editing "packet" still consists of mac address + msg(ip) + port.
I had no multiple retry dialog, you?
However, I agree it is not a hoop you would want to ask users to jump through.
I agree that it is really unfriendly but this technique is used by many popular apps like Xender, Zapya which are file sharing apps. That's where I got the idea from in the first place. Having said that, I'd always use this only as a last resort.