sharp-jsonrpc/net/JSONClient.cs

74 lines
1.7 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using Newtonsoft.Json.Linq;
namespace sharp.jsonrpc.net
{
public delegate void JSONConnectionClosed(JSONClient sender);
public class JSONClient
{
public event JSONConnectionClosed OnConnectionClosed;
Socket socket;
NetworkStream stream;
TextReader reader;
TextWriter writer;
public JSONClient(Socket socket)
{
this.socket = socket;
this.stream = new NetworkStream(socket);
this.reader = new StreamReader(this.stream);
this.writer = new StreamWriter(this.stream);
}
public void Close(){
this.socket.Close();
if (OnConnectionClosed != null){
OnConnectionClosed(this);
}
}
public bool Connected { get { return this.socket.Connected; } }
public JToken readJSON(){
if (!Connected){
throw new IOException("JSONClient is not connected");
}
string line = reader.ReadLine();
while ((line != null) && line.Equals("")){
line = reader.ReadLine();
}
if (line == null){
Close();
throw new IOException("JSONCLient connection closed");
}
Console.WriteLine("JSONClient: readJSON(): {0}",line);
return JToken.Parse(line);
}
public void writeJSON(JToken json){
string line = json.ToString().Replace("\n","").Replace("\r","");
Console.WriteLine("JSONClient: writeJSON(): {0}",line);
this.writer.WriteLine(line);
this.writer.Flush();
}
public void writeJSONRPC(UInt64 id,JToken result,JToken error){
JObject reply = new JObject(
new JProperty("id", id),
new JProperty("jsonrpc", "2.0"),
new JProperty("result", result),
new JProperty("error", error)
);
writeJSON(reply);
}
}
}