Basic Html5 Socket issue - html

Just wondering if some can help me with the issue, below is my web socket Helloserver code and the client.htm code. After starting the Helloserver we run the client and notice that it does not connect to the server, will really appreciate if someone can help.
Here is the client.htm:
<!doctype html>
<html>
<head>
<title>Web Sockets: Connecting to the Server</title>
<link rel="Stylesheet" href="/global.css" type="text/css" />
</head>
<body>
<div id="container">
<h1>Connecting to Web Socket Server</h1>
<ul id="log"></ul>
</div>
</body>
<script src="../scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script>
$(function () {
function logMsg(message) {
$("#log").append("<li>" + message + "</li>");
}
logMsg("Attempting to connect to socket server");
var server = null;
try {
server = new WebSocket("ws://localhost:8181/server");
server.addEventListener("message", messageHandler, false);
server.addEventListener("open", openHandler, false);
server.addEventListener("close", closeHandler, false);
}
catch (e) {
}
function openHandler(e) {
logMsg("Connection opened");
}
function closeHandler(e) {
logMsg("Connection closed");
}
function messageHandler(e) {
logMsg("Server says: " + e.data);
}
});
</script>
</html>
Here is the server code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SocketServer.Models;
using Nugget;
namespace SocketServer
{
class HelloServer : ISocketServer
{
private string _serverPath = string.Empty;
private WebSocketServer _server = null;
private string _input = string.Empty;
public string Input
{
set { this._input = value; }
}
public void Initialize(string serverPath, string originServerAndPort)
{
this._server = new WebSocketServer(8181, originServerAndPort, "ws://localhost:8181");
this._server.RegisterHandler<Socket>(serverPath);
Nugget.Log.Level = LogLevel.None;
}
public void Start()
{
this._server.Start();
}
public void Send()
{
this._server.SendToAll(this._input);
}
}
}
Here is the console code to start the server:
using System;
using Nugget;
namespace SocketServer
{
class Server
{
static void Main(string[] args)
{
ISocketServer server = null;
Console.WriteLine();
Console.WriteLine("Welcome to the socket server.");
Console.WriteLine();
Console.WriteLine("Which server type would you like to create?");
Console.WriteLine(" 1) Hello World Server");
Console.WriteLine(" 2) Stocks Server");
Console.WriteLine();
string input = Console.ReadLine();
if (input == "1")
{
server = new HelloServer();
server.Initialize("/server", "http://localhost:2709");
Console.WriteLine("");
Console.WriteLine("The Hello World Server is now available under ws://localhost:8181/server.");
Console.WriteLine("");
}
else if (input == "2")
{
server = new StockServer();
server.Initialize("/stocks", "http://localhost:2709");
Console.WriteLine("");
Console.WriteLine("The Stocks Server is now available under ws://localhost:8181/stocks.");
Console.WriteLine("");
}
else
{
Console.WriteLine("");
Console.WriteLine(string.Format("Sorry, {0} is not a valid option.", input));
Console.WriteLine("");
}
if (server != null)
{
server.Start();
input = string.Empty;
while (input != "exit")
{
server.Input = input;
server.Send();
input = Console.ReadLine();
}
}
Console.WriteLine("");
Console.WriteLine("Closing socket server.");
Console.WriteLine("");
}
}
}
The issue we are having is that after the client is run it gives this message and does not connect to the server:
Attempting to connect to socket server
Connection closed
Any help will be appreciated.

Make sure that websockets are enabled in the browser you use.
In the other hand you may want to revise this line in client.html
server = new WebSocket("ws://localhost:8181/server");
Is the "/server" part necessary ?

Related

Internal error when setting up cache

Im trying to set the cache for my app.
My problem is that I get error 500 when Im trying to use it.
This is my code:
<?php
include_once '/var/www/libs/mainCache/fatfree-master/lib/base.php';
class CacheManager
{
private $cache;
private $isDebug;
const GYM_LIST = "gym_list";
const CHALLENGES_LIST = "challnges_list";
function __construct($isDebug = false)
{
$this->cache = \Cache::instance();
$this->isDebug = $isDebug;
$folder = $this->isDebug ? "/var/www/soFitTest/cache/" : "/var/www/soFit/cache/";
$this->cache->load(true, "folder=".$folder);
}
public function exists($id)
{
return $this->cache->exists($id);
}
public function set($id, $value)
{
return $this->cache->set($id, $value);
}
public function get($id)
{
return $this->cache->get($id);
}
public function clear($id)
{
return $this->cache->clear($id);
}
}
When I run my code:
$cacheManager = new CacheManager(true);
$gmyList = $cacheManager->get(CacheManager::GYM_LIST);
if($gmyList)
{
$result = $gmyList;
$result["cache"] = "true";
}
else
{
$result = $gymManager->getGymsList();
$result["cache"] = "false";
$cacheManager->set(CacheManager::GYM_LIST, $result);
}
I get:
<!DOCTYPE html>
<html>
<head>
<title>500 Internal Server Error</title>
<style>code{word-wrap:break-word;color:black}.comment,.doc_comment,.ml_comment{color:dimgray;font-style:italic}.variable{color:blueviolet}.const,.constant_encapsed_string,.class_c,.dir,.file,.func_c,.halt_compiler,.line,.method_c,.lnumber,.dnumber{color:crimson}.string,.and_equal,.boolean_and,.boolean_or,.concat_equal,.dec,.div_equal,.inc,.is_equal,.is_greater_or_equal,.is_identical,.is_not_equal,.is_not_identical,.is_smaller_or_equal,.logical_and,.logical_or,.logical_xor,.minus_equal,.mod_equal,.mul_equal,.ns_c,.ns_separator,.or_equal,.plus_equal,.sl,.sl_equal,.sr,.sr_equal,.xor_equal,.start_heredoc,.end_heredoc,.object_operator,.paamayim_nekudotayim{color:black}.abstract,.array,.array_cast,.as,.break,.case,.catch,.class,.clone,.continue,.declare,.default,.do,.echo,.else,.elseif,.empty.enddeclare,.endfor,.endforach,.endif,.endswitch,.endwhile,.eval,.exit,.extends,.final,.for,.foreach,.function,.global,.goto,.if,.implements,.include,.include_once,.instanceof,.interface,.isset,.list,.namespace,.new,.print,.private,.public,.protected,.require,.require_once,.return,.static,.switch,.throw,.try,.unset,.use,.var,.while{color:royalblue}.open_tag,.open_tag_with_echo,.close_tag{color:orange}.ini_section{color:black}.ini_key{color:royalblue}.ini_value{color:crimson}.xml_tag{color:dodgerblue}.xml_attr{color:blueviolet}.xml_data{color:red}.section{color:black}.directive{color:blue}.data{color:dimgray}
</style>
</head>
<body>
<h1>Internal Server Error</h1>
<p>mkdir(): Permission denied</p>
</body>
</html>
My folder is set to full permissions:

How to update data continuously in UI text box control using windows phone application

Im developing a small Tcp Client Socket application in windows phone. Actually i have a text box, in that whatever the data received from a TCP server, should update continuously in UI text box control.
while (val)
{
result = Receive();
Dispatcher.BeginInvoke((Action)(() =>
{
txtOutput.Text += result;
}));
}
Here in above code, method receive() will receive string data and should update in textbox control but it is not happening,no data is updating to it.
Can any one suggest, how can i resolve this.
Just telling you what i have been advised, "avoid Dispatcher, CoreDispatcher, etc. There are always better solutions."
Below is the piece of code worked for me for both wp8 and wp8.1 WinRT app,
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
where UpdateTicker() method contains your instructions, in this case...
public void UpdateTicker()
{
result = Receive();
txtOutput.Text += result;
}
Hope this helps...
Thanks for everyone, who given a valuable response for my post.
Hi Nishchith,
I tried your code, but it dint works for me
Here is my logic used to update textbox continuously with data received from TCP server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp3.Resources;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using Windows.Phone.Networking;
using System.Threading.Tasks;
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
Socket _socket = null;
static ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 1000;
const int MAX_BUFFER_SIZE = 2048;
const int ECHO_PORT = 9055; // The Echo protocol uses port 7 in this sample
const int QOTD_PORT = 49152; // The Quote of the Day (QOTD) protocol uses port 17 in this sample
string result = string.Empty;
public MainPage()
{
InitializeComponent();
}
private void btnEcho_Click(object sender, RoutedEventArgs e)
{
SocketClient client = new SocketClient();
Connect(txtRemoteHost.Text, ECHO_PORT);
//close();
}
public void Connect(string hostName, int portNumber)
{
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
result = e.SocketError.ToString();
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(2000);
_socket.ConnectAsync(socketEventArg);
Thread.Sleep(5000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
bool val;
if (result == "Success")
{
val = true;
}
else
{
val = false;
}
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
}
public void UpdateTicker()
{
result = Receive();
string[] strsplit = result.Split(' ');
txtOutput.Text = strsplit[1];
}
public string Receive()
{
string response = "Operation Timeout";
if (_socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(1000);
_socket.ReceiveAsync(socketEventArg);
Thread.Sleep(1000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
public void Close()
{
if (_socket != null)
{
_socket.Close();
}
}
}
}

I am getting error in LoginAsync method during wp8 App development for sky drive

I am developing a windows phone 8 application to access sky drive. I am getting following error when I call LoginAsync() method-
An exception of type 'Microsoft.Live.LiveAuthException' occurred in mscorlib.ni.dll but was not handled in user code
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Live;
namespace SkyDriveApp
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
LiveConnectClient client;
public MainPage()
{
InitializeComponent();
}
public async void Auth()
{
string clientId = "My_client_id";
LiveAuthClient auth = new LiveAuthClient(clientId);
// var result = await auth.InitializeAsync(new[] { "wl.basic", "wl.signin", "wl.skydrive_update" });
var result = await auth.LoginAsync(new[] { "wl.basic", "wl.signin", "wl.skydrive_update" });
if (result.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(result.Session);
tbMessage.Text = "Connected!";
}
}
private void btnLogin_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
Auth();
}
}
}
I see that you are using provided login buton, try this:
In xaml:
<live:SignInButton Name="skyBtn" ClientId="your client ID" Scopes="wl.signin wl.skydrive wl.skydrive_update" Branding="Skydrive" TextType="Login"/>
In code behind:
private void skyBtn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
session = e.Session;
client = new LiveConnectClient(session);
tbMessage.Text = "Connected!";
}
else tbMessage.Text = "Not Connected!";
if (e.Error != null)
{
tbMessage.Text = "Not Connected!";
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Error.Message);
});
}
}

MvvmCross: NotImplementedException calling EnsureFolderExists method of IMvxFileStore

I'm developing my first Windows Store App, using MvvmCross framework and I have a problem with images management. In particular I have the following simple ViewModel in my PCL project, and a Store project with a button bound with AddPictureCommand.
public class FirstViewModel : MvxViewModel
{
IMvxPictureChooserTask _pictureChooserTask;
IMvxFileStore _fileStore;
public FirstViewModel(IMvxPictureChooserTask pictureChooserTask, IMvxFileStore fileStore)
{
_pictureChooserTask = pictureChooserTask;
_fileStore = fileStore;
}
private byte[] _pictureBytes;
public byte[] PictureBytes
{
get { return _pictureBytes; }
set
{
if (_pictureBytes == value) return;
_pictureBytes = value;
RaisePropertyChanged(() => PictureBytes);
}
}
public ICommand AddPictureCommand
{
get { return new MvxCommand(() =>
{
_pictureChooserTask.ChoosePictureFromLibrary(400, 95, pictureAvailable, () => { });
}); }
}
private void pictureAvailable(Stream stream)
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
PictureBytes = memoryStream.ToArray();
GenerateImagePath();
}
private string GenerateImagePath()
{
if (PictureBytes == null) return null;
var RandomFileName = "Image" + Guid.NewGuid().ToString("N") + ".jpg";
_fileStore.EnsureFolderExists("Images");
var path = _fileStore.PathCombine("Images", RandomFileName);
_fileStore.WriteFile(path, PictureBytes);
return path;
}
}
The problem is that the method _fileStore.EnsureFolderExists("Images");
gives me the an "NotImplementedException" with message: "Need to implement this - doesn't seem obvious from the StorageFolder API".
Has anyone already seen it before?
Thank you
This not implemented exception is documented in the wiki - see https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#File
It should be fairly straightforward to implement these missing methods if they are required. Indeed I know of at least 2 users that have implemented these - but sadly they've not contributed them back.
to implement them, just
fork (copy) the code from https://github.com/MvvmCross/MvvmCross/blob/v3/Plugins/Cirrious/File/Cirrious.MvvmCross.Plugins.File.WindowsStore/MvxWindowsStoreBlockingFileStore.cs
implement the missing methods using the winrt StorageFolder apis
in your Store UI project, don't load the File plugin - so comment out or remove the File bootstrap class.
during setup, register your implementation with ioc using Mvx.RegisterType - e.g.:
protected override void InitializeFirstChance()
{
base.InitializeFirstChance();
Cirrious.CrossCore.Mvx.RegisterType<IMvxFileStore, MyFileStore>();
}
For more on using ioc, see https://github.com/MvvmCross/MvvmCross/wiki/Service-Location-and-Inversion-of-Control
For more on customising the setup sequence, see https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup
Following Stuart's suggestions I've implemented the following methods for Windows 8 Store App:
public bool FolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
return false;
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in FolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
return true;
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
public void EnsureFolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
var localFolder = ToFullPath(string.Empty);
var storageFolder = StorageFolder.GetFolderFromPathAsync(localFolder).Await();
storageFolder.CreateFolderAsync(folderPath).Await();
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in EnsureFolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - doesn't seem obvious from the StorageFolder API");
//var folder = StorageFolder.GetFolderFromPathAsync(ToFullPath(folderPath)).Await();
}
The third method we need to implement is DeleteFolder(string folderPath, bool recursive). Unfortunately StorageFolder method "DeleteFolder" doesn't have a "recursive" parameter. So I should implement DeleteFolder ignoring it:
public void DeleteFolder(string folderPath, bool recursive)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
storageFolder.DeleteAsync().Await();
}
catch (FileNotFoundException)
{
//Folder doesn't exist. Nothing to do
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in DeleteFolder - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
or I should check if the folder is empty before to delete it if "recursive" equals false.
Better implementations are welcomed.

How can I save a JSON response to a file in unity3D for ios and android

I'm working on a 2D mobile game for ios and android using Unity3D.
The game requires to save a JSON response to a file.
I use NGUI and MiniJSON for that.
I want to know how to implement that starting from www function to get JSOn response and save it to a file(including path) and load it from other script.
if it is too much, just give me a example for that.
Thank you
I haven't tested the code yet, but it might give you an idea :-)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class WWWJsonTest : MonoBehaviour
{
private const float SECONDS_BEFORE_TIMEOUT = 10;
private const string URL = "INSERT URL HERE";
private const string FILE_PATH = "INSERT FILE PATH";
public void DownloadAndSave()
{
StartCoroutine(DownloadCoroutine());
}
public Dictionary<object, object> GetSavedData()
{
// Use ReadContents() and do your MiniJSON magic here
return null;
}
private IEnumerator DownloadCoroutine()
{
var requestHeaders = new Hashtable()
{
{ "Connection", "close"},
{ "Accept", "application/json"}
};
using(var request = new WWW(URL, null, requestHeaders))
{
float timeStarted = Time.realtimeSinceStartup;
while(!request.isDone)
{
// Check if the download times out
if(Time.realtimeSinceStartup - timeStarted > SECONDS_BEFORE_TIMEOUT)
{
Debug.Log("Download timed out");
yield break;
}
yield return null;
}
// Check for other errors
if(request.error != null)
{
Debug.Log(request.error);
yield break;
}
SaveContents(request.text);
}
}
private string ReadContents()
{
string ret;
using(FileStream fs = new FileStream(FILE_PATH, FileMode.Open))
{
BinaryReader fileReader = new BinaryReader(fs);
ret = fileReader.ReadString();
fs.Close();
}
return ret;
}
private void SaveContents(string text)
{
using(FileStream fs = new FileStream(FILE_PATH, FileMode.Create))
{
BinaryWriter fileWriter = new BinaryWriter(fs);
fileWriter.Write(text);
fs.Close();
}
}
}