Could you help me with this:
I need to create a connection file to a PLC through ModbusClient, a separate file from the Main, but within the same solution. I have it like this:
enter image description here
And this is the code:
namespace HMIOperations
{
internal class Connection_PLC
{
public ModbusClient Connect(ModbusClient modbusClientreturn)
{
IPAddress plcIp = IPAddress.Parse("192.168.3.250");
int plcPort = 49501;
modbusClientreturn = new ModbusClient
{
IpAddress = plcIp,
Port = plcPort
};
//Connect to PLC
try
{
modbusClientreturn.Connect();
}
catch (Exception exception)
{
MessageBox.Show("Conexion no establecida con el PLC.\n Intenta de nuevo.");
}
return modbusClientreturn;
}
}
}
My question is, how can I use this file in the main and in the other files where I need it. That I have to do?
The problem can be solved like this:
Class internal : you can just use the same namespace.
Try this:
Public class Connection_PLC
Replace this solution with the following code that has been tested and my currently used one.
using EasyModbus;
ModbusClient Plc= new ModbusClient();
private Thread Data_thread = (Thread)null;
private int[] Registerlist;
private void connect()
{
Plc.Disconnect();
ServerIP = "192.168.3.250";
Plc.Connect(ServerIP, 502);
this.Data_thread = new Thread(new
ThreadStart(this.getmessage));
this.Data_thread.Start();
}
private void getmessage()
{
while (Plc.Connected)
{
Registerlist= Plc.ReadHoldingRegisters(8,1);//yourregister
}
}
Related
I have an Android application created in C# using Xamarin.
This is essentially a web browser with some additional functionalities and now I would like add the option to set up a proxy to use. In the application I use WebView for connection to websites.
I tried to implement solution from this topic (How can I set ProxySettings and ProxyProperties on Android Wi-Fi connection using Java?), but there is no linkProperties in WifiConfiguration. This is how it looks like:
private static Java.Lang.Object getField(Java.Lang.Object obj, String name)
{
Field f = obj.Class.GetField(name);
Java.Lang.Object o = f.Get(obj);
return o;
}
public void SetHttpProxy(string proxyServerAddress, int proxyServerInt)
{
try
{
var wifiManager = context.GetSystemService(Context.WifiService) as WifiManager;
if (!wifiManager.IsWifiEnabled)
return;
var configurationList = wifiManager.ConfiguredNetworks;
var cur = wifiManager.ConnectionInfo.NetworkId;
var configuration = configurationList.FirstOrDefault(conf => conf.NetworkId == cur);
getField(configuration, "linkProperties");
}
catch (Exception e)
{
throw;
}
}
Here is solution that works for 4., 5., 6.* and 7.* Android OS versions for sure:
public static void SetProxy(WebView webView, string host, int port, bool bypass)
{
Context appContext = webView.Context.ApplicationContext;
JavaSystem.SetProperty("http.proxyHost", host);
JavaSystem.SetProperty("http.proxyPort", port + "");
JavaSystem.SetProperty("https.proxyHost", host);
JavaSystem.SetProperty("https.proxyPort", port + "");
if (bypass)
JavaSystem.SetProperty("http.nonProxyHosts", BYPASS_PATTERN);
try
{
Class applictionCls = Class.ForName(APPLICATION_CLASS_NAME);
Field loadedApkField = applictionCls.GetField("mLoadedApk");
loadedApkField.Accessible = true;
Object loadedApk = loadedApkField.Get(appContext);
Class loadedApkCls = Class.ForName("android.app.LoadedApk");
Field receiversField = loadedApkCls.GetDeclaredField("mReceivers");
receiversField.Accessible = true;
ArrayMap receivers = (ArrayMap) receiversField.Get(loadedApk);
foreach (Object receiverMap in receivers.Values())
{
foreach (Object rec in Extensions.JavaCast<ArrayMap>(receiverMap).KeySet())
{
Class clazz = rec.Class;
if (clazz.Name.Contains("ProxyChangeListener"))
{
Method onReceiveMethod = clazz.GetDeclaredMethod("onReceive", Class.FromType(typeof(Context)), Class.FromType(typeof(Intent)));
Intent intent = new Intent(Android.Net.Proxy.ProxyChangeAction);
onReceiveMethod.Invoke(rec, appContext, intent);
}
}
}
}
catch (Exception)
{
}
}
I have a WCF message inspector which inspects requests and responses: Message. The inspector works fine. A Message object can only be read once so once you read it, you cannot simply propagate as WCF will complain that the message has been read. Therefore, I am creating a brand new copy of the message and propagating that.
I have designed a class that allows message reading and after the caller has read whatever they want, they need to call Close which will return a copy of the message. Here is the skeleton of my class:
using System.ServiceModel.Channels;
internal abstract class MessageReader
{
internal string ReadSomething(string id)
{
// Return string
}
internal string ReadSomethingElse(string id)
{
// Return string
}
internal Message Close()
{
// Create copy and return it.
}
}
Users of my class may forget to call Close() which is fine because WCF will yell at them. Right now I have documentation to let users know they need to call Close().
Here is the question
Is there a pattern, or something similar, to C#'s using construct but one which returns an object at the end? This will be really convenient because then users of my class can just use a construct like that and at the end it will return the copy of the message. Something like this:
UsingSomeConstruct(var reader = new MessageReader(ref originalMessage))
{
var a = reader.ReadSomething("something");
var b = reader.ReadSomethingElse("something");
// Do something with what was read
}
// At this point originalMessage will be the copy of the message and no longer the original message.
EDIT
I thought about hacking IDisposable to achieve this but I am NOT going to do it that way so looking for other ideas.
There is no such language construct of course.
What I could suggest is to use IDisposable for cleaning up, and add ref Message message argument to each ReadXXX method. I know it will not be so convenient for your users, but from the other side they cannot forget passing the parameter.
So the implementation would be something like this:
internal class MessageReader : IDisposable
{
private MessageBuffer buffer;
private Message message;
private void Release()
{
if (buffer == null) return;
buffer.Close();
buffer = null;
message = null;
}
protected void OnReadRequest(ref Message message)
{
if (message == null) throw new ArgumentNullException("message");
if (this.message == message) return;
Release();
this.buffer = message.CreateBufferedCopy(int.MaxValue);
message = this.message = buffer.CreateMessage();
}
public void Dispose()
{
Release();
}
internal string ReadSomething(ref Message message, string id)
{
OnReadRequest(ref message);
// Return string
}
internal string ReadSomethingElse(ref Message message, string id)
{
OnReadRequest(ref message);
// Return string
}
}
and the sample usage:
using (var reader = new MessageReader())
{
var a = reader.ReadSomething(ref originalMessage, "something");
var b = reader.ReadSomethingElse(ref originalMessage, "something");
// Do something with what was read
}
// At this point originalMessage will be the copy of the message and no longer the original message.
The way I'd do this is as follows:
public MessageReader: IDisposable
{
public static MessageReader Create(ref Message message)
{
var buffer = message.CreateBufferedCopy(/*whatever is fit*/);
try
{
var reader = new MessageReader(buffer);
message = buffer.CreateMessage();
return reader;
}
catch
{
buffer.Close();
throw;
}
}
private readonly MessageBuffer buffer;
private bool disposed;
private MessageReader(MessageBuffer buffer) { this.buffer = buffer; }
public void Dispose()
{
if (disposed)
return;
buffer.Close();
disposed = true;
}
public string Read(string id)
{
var newCopy = buffer.CreateMessage();
//work with new copy...
}
}
And you'd simply use it like this:
using (var reader = MessageReader.Create(ref message))
//message here is already an untouched copy with no need of user active
//intervention and is never touched again by the reader.
{
var a = reader.Read("something"); //reads copy
...
}
IMHO, this is as clean as it can be. Note that MessageReader implements IDisposable exclusively because it holds a reference to the disposable private MessageBuffer.
Thanks to all the help from #InBetween, #quetzalcoatl, and #Ivan Stoev. Upvoted your answers because it helped me arrive at the following.
In the constructor, I create a copy of the message and set the original message to the copy. Since the status of this message is Created WCF will be happy propogating it. I create another copy and use that for reading multiple times.
#Ivan said but what if the user does not ask for anything to be read then the copying was wasted work. That is a good point but in my case, this is an interceptor and all messages are intercepted to be read.
Here is the code I ended up with suggestions from all of you:
public class MessageReader : IDisposable {
private readonly Message message;
public MessageReader(ref Message originalMessage) {
using( var buffer = originalMessage.CreateBufferedCopy( int.MaxValue ) ) {
// Keep original message for reading
this.message = buffer.CreateMessage();
// Set original message to a copy of the original
originalMessage = buffer.CreateMessage();
}
}
public int ReadSomething(string id) {
// Read from this.message;
}
public int ReadSomethingElse(string id) {
// Read from this.message;
}
public void Close() {
this.Dispose();
}
public void Dispose() {
this.message.Close();
}
}
The caller can either use it in a using block or without it. The using block is used for good reasons and not as a hack.
public object AfterReceiveRequest(ref Message request, IClientChannel channel,
InstanceContext instanceContext) {
try {
using( var rdr = new MessageReader(ref request) ) {
var value= rdr.ReadSomething( someIdentifier );
return value;
}
}
catch( System.Exception ex ) {
throw CreateFault( ex, request );
}
}
Nope, there is no such construct. It is simply too specific to exist there out of the box. There are extension methods which often are very helpful, but you won't be able to use them on this ref Message parameter..
However, if you are willing to use ref at all, then why dont simply include all that logic it in Reader's constructor?
Here's an example, somewhat contrived, but it should show what I mean. Like others mentioned in comments, I also suggest implementing IDisposable on the Reader object instead of Close, so I included that already.
TL;DR: In example below, the most important thing is in Reader(ref msg) constructor which clones the message, copies the data, and replaces the original message with a safe-message class which can be read many times..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
// real-world variables, keep them typed as base Message
// to be able to silently replace them with different objects
Message original1;
Message original2;
// let's construct some one-time readable messages
{
var tmp1 = new OneTimeMessage();
tmp1.data["mom"] = "dad";
tmp1.data["cat"] = "dog";
original1 = tmp1;
var tmp2 = new OneTimeMessage();
tmp2.data["mom"] = "dad";
tmp2.data["cat"] = "dog";
original2 = tmp2;
}
// test1 - can't read twice
Console.WriteLine("test0A:" + original1.GetData("mom"));
//Console.WriteLine("test0B:" + original1.GetData("mom")); // fail
// test2 - can read twice with Reader's help
var backup1 = original2;
using(var rd1 = new Reader(ref original2))
{
Console.WriteLine("test1A:" + rd1.ReadSomething("mom"));
}
var backup2 = original2;
using(var rd2 = new Reader(ref original2))
{
Console.WriteLine("test1A:" + rd2.ReadSomething("mom"));
//^ ok - becase Reader replaced 'original2' with SafeMessage
}
// test3: Reader's ctor is intelligent
// so no more SafeMessages created during future usage
var backup3 = original2;
using(var rd3 = new Reader(ref original2))
{
}
var backup4 = original2;
using(var rd4 = new Reader(ref original2))
{
}
Console.WriteLine("checking for copies:" + (original2 == backup1));
Console.WriteLine("checking for copies:" + (original2 == backup2));
Console.WriteLine("checking for copies:" + (original2 == backup3));
Console.WriteLine("checking for copies:" + (original2 == backup4));
}
}
}
public abstract class Message
{
public abstract string GetData(string id);
}
public class OneTimeMessage : Message // this models your current one-time-readable message
{
public IDictionary<string, string> data = new Dictionary<string, string>();
public override string GetData(string id)
{
var tmp = data[id];
data.Remove(id);
// that's nonsense, but I want to show that you can't
// read the same thing twice from this object
return tmp;
}
}
public class SafeMessage : Message
{
public IDictionary<string, string> data;
public override String GetData(string id)
{
return data[id];
}
public SafeMessage(Message msg)
{
// read out the full msg's data and store it
// since this is example, we can do it in a pretty simple way
// in your code that will probably be more complex
this.data = new Dictionary<string,string>(((OneTimeMessage)msg).data);
}
}
public class Reader : IDisposable
{
private Message message;
public Reader(ref Message src)
{
src = src is SafeMessage ? src : new SafeMessage(src);
this.message = src;
}
public string ReadSomething(string id){ return message.GetData(id); }
public void Dispose(){ Close(); }
public void Close(){ message=null; Console.WriteLine("reader closed"); }
}
EDIT: improved example
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text.RegularExpressions;
using System.Xml;
namespace MyProgram
{
public class Program
{
public static void Main(string[] args)
{
// real-world variables, keep them typed as base Message
// to be able to silently replace them with different objects
Message original1;
Message original2;
// let's construct some one-time readable messages
{
original1 = new TheMessage("dad", "dog");
original2 = new TheMessage("dad", "dog");
}
// test1 - can't read twice
Console.WriteLine("test0A:" + original1.GetReaderAtBodyContents().ReadOuterXml());
// Console.WriteLine("test0B:" + original1.GetReaderAtBodyContents().ReadOuterXml()); // fail: InvalidOperationException - it was already read
// test2 - can read ONCE with Reader's help, but the message is replaced and is usable again
var backup1 = original2;
using (var rd1 = new ReaderOnce(ref original2))
{
Console.WriteLine("is message replaced after opening Reader:" + (original2 != backup1));
Console.WriteLine("test1A:" + rd1.ReadBodyXml());
// Console.WriteLine("test1B:" + rd1.ReadBodyXml()); // fail: InvalidOperationException - it was already read
}
// test3 - can read MANY TIMES with ReaderMany's help
// also note we use 'original2' again, which was already used above, so in fact ReaderOnce really works as well
var backup2 = original2;
using (var rd1 = new ReaderMany(ref original2))
{
Console.WriteLine("is message replaced after opening Reader:" + (original2 != backup2));
Console.WriteLine("test2A:" + rd1.ReadBodyXml());
Console.WriteLine("test2B:" + rd1.ReadBodyXml()); // ok
}
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
}
// solution1
public class ReaderOnce : IDisposable
{
private Message localCopy;
public ReaderOnce(ref Message src)
{
// create a WCF MessageBuffer to assist in copying messages
// btw. I suppose you should set some sane limit instead of that below
using (var tempBuffer = src.CreateBufferedCopy(int.MaxValue))
{
src = tempBuffer.CreateMessage(); // FIRST copy for outer use
localCopy = tempBuffer.CreateMessage(); // SECOND copy for internal use in the Reader
}
}
public void Dispose() { Close(); }
public void Close()
{
localCopy.Close(); // but that does NOT affect FIRST copy sent to outer scope outside reader
Console.WriteLine("reader closed");
}
public string ReadBodyXml() // careful: that's again ONE TIME readable
{
return localCopy.GetReaderAtBodyContents().ReadOuterXml();
}
}
// solution2
public class ReaderMany : IDisposable
{
private MessageBuffer localBuffer;
public ReaderMany(ref Message src)
{
localBuffer = src.CreateBufferedCopy(int.MaxValue);
src = localBuffer.CreateMessage(); // FIRST copy for outer use
}
public void Dispose() { Close(); }
public void Close()
{
localBuffer.Close();
Console.WriteLine("reader closed");
}
public string ReadBodyXml() // this is readable multiple times
{
using (var tmp = localBuffer.CreateMessage())
return tmp.GetReaderAtBodyContents().ReadOuterXml();
}
}
// let's fake some Message type to have something to test the Reader on
public class TheMessage : Message
{
public override MessageHeaders Headers => _mh;
public override MessageProperties Properties => _mp;
public override MessageVersion Version => _mv;
private MessageHeaders _mh;
private MessageProperties _mp;
private MessageVersion _mv;
private string data1;
private string data2;
// btw. below: surprise! XmlDictionaryWriter is in "System.Runtime.Serialization", not in "System.Xml"
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteStartElement("foo");
writer.WriteAttributeString("data1", data1);
writer.WriteAttributeString("data2", data2);
writer.WriteEndElement();
}
public TheMessage(string data1, string data2)
{
// remember, this class is just an example, you will work on your own messages you already have
_mv = MessageVersion.Soap12;
_mh = new MessageHeaders(_mv);
_mp = new MessageProperties();
// below: yeah, that's super-naive and wrong, but that's an example
this.data1 = data1;
this.data2 = data2;
}
}
There is no language construct in c# that does what you are asking. As stated in comments, you could abuse IDisposable and the language and use a using block to achieve what you want.
But, I fail see what you are gaining, you are just punting the problem; now users will need to remember to use usinginstead of Close. The latter is simple and clean, the former uses a very known language construct to do something different to what it was thought for, something that will potentially be very confusing.
I am using a serial port object that was generated by the designer in C# (non static).
I need to be able to access it from methods that are static in different classes (I know it is a bad practice but that is what I inherit)
The port access use the below code.
public bool Read_Board_Port()
{
byte[] bData = new byte[256];
string message;
bool sucess = false;
try
{
if (!(serialBoardPort.IsOpen == true))
Connect_To_Board(Globals.BoardportName, Globals.BoardbaudRate, Globals.Boardparity, Globals.BoardstopBits, Globals.BoarddataBits);
if(CMDDirect || Globals.HostCommandString)
{
serialBoardPort.ReadTimeout = 1000; // Timeout if no answer from the port.
message = serialBoardPort.ReadLine();
Globals.RXBoardBuff = Encoding.UTF8.GetBytes(message);
Write_To_Console_Dr(message);
sucess = true;
}
else
{
serialBoardPort.Read(Globals.RXBoardBuff, 0, Constants.RXBOARDBUFFSIZE);
if (Check_Command_Correct(Globals.RXBoardBuff, Globals.CommandOut))
sucess = true;
else
{
Write_Error_To_Console_Dr(Constants.ERRORDATAFROMBOARDPORT);
sucess = false;
}
}
}
catch
{
MessageBox.Show(Constants.ERRORNODATABOARPORT);
sucess = false;
}
return sucess;
}
If I declare new a different instance of the serial port will be used, I need to use the port that is already open.
Thanks
As stated by #Matthew Spencer you should pass the serial port as a parameter to the static methods that needs it. First create a method on your board class or whatever its name is that returns the instance of your serial port. Then use it to get the serial port for use to the static methods you mentioned.
Something like this should be what you need..
public bool Read_Board_Port()
{
byte[] bData = new byte[256];
string message;
bool sucess = false;
try
{
if (!(serialBoardPort.IsOpen == true))
Connect_To_Board(Globals.BoardportName, Globals.BoardbaudRate, Globals.Boardparity, Globals.BoardstopBits, Globals.BoarddataBits);
if(CMDDirect || Globals.HostCommandString)
{
serialBoardPort.ReadTimeout = 1000; // Timeout if no answer from the port.
message = serialBoardPort.ReadLine();
Globals.RXBoardBuff = Encoding.UTF8.GetBytes(message);
Write_To_Console_Dr(message);
sucess = true;
}
else
{
serialBoardPort.Read(Globals.RXBoardBuff, 0, Constants.RXBOARDBUFFSIZE);
if (Check_Command_Correct(Globals.RXBoardBuff, Globals.CommandOut))
sucess = true;
else
{
Write_Error_To_Console_Dr(Constants.ERRORDATAFROMBOARDPORT);
sucess = false;
}
}
}
catch
{
MessageBox.Show(Constants.ERRORNODATABOARPORT);
sucess = false;
}
return sucess;
}
// since serialBoardPort seems to be a globally declared variable
public SerialPort GetInstance()
{
return serialBoardPort;
}
// Let's name your class as board..
// on somewhere in your app code:
Board board = // GetValue
SerialPort boardSerialPort = board.GetInstance();
ClassXXX.StaticMethodNeedsPort(boardSerialPort); // pass your serial port to the static method
UPDATE: Since there was a bit of misunderstanding as the questioner said..
I suggest using an IoC container, read more here
Here is what I use. Normally this is already a part of frameworks such as MVVM Cross.
CODE:
public class Core
{
private static readonly Core instance = new Core();
private Dictionary<Type, object> container;
private Core()
{
container = new Dictionary<Type, object>();
}
public void RegisterSingleton<T>(T value) where T : class
{
Type type = typeof(T);
if (!container.ContainsKey(type))
container.Add(type, value);
}
public T GetSingleton<T>() where T : class
{
Type type = typeof(T);
if (container.ContainsKey(type))
return (T)container[type];
else
throw new Exception("Singleton instance not registered.");
}
public void RemoveSingleton<T>() where T : class
{
Type type = typeof(T);
if (container.ContainsKey(type))
container.Remove(type);
}
public void ClearSingletons()
{
container.Clear();
}
public static Core Instance
{
get { return instance; }
}
}
When your application loads add this line:
Core.Instance.ClearSingletons();
In case it already has a port upon loading since it is auto-generated by C# just register the instance too..
Core.Instance.RegisterSingleton(MySerialPortObject); // Or class. Can be object
On the part of the application when you need the port just get its instance like this...
SerialPort _myPort = Core.Instance.GetSingleton<X>(); // Where X value is the type of your registered object. If you are registering a SerialPort then replace X with SerialPort.
You can get the instance of your port anywhere you like. When I use this I normally register implementation of interfaces so that I can get it like
IFileHandler _fileHandler = Core.Instance.GetSingleton<IFileHandler>() // Where I registered the class that implements IFileHandler upon the startup of my application
Sorry for the long answer.
I want to implement following functionality :
fetching one by one packets from pcap file. I need to separate packets depending on their protocol type. so basically i should be able to change packet objects like ip address
language i am using is c#
So is this possible to implement using Pcap.net ?
Is there standard code available with anybody ? please provide me that.
Thanks a lot
ftm
Yes, it is possible.
See "Reading packets from a dump file" in Pcap.Net's tutorial.
first, download PcapDotNet.Core.dll and PcapDotNet.Packets.dll and after create a class
public class Session
{
private IList<Packet> _PacketsSequence;
public IList<Packet> PacketsSequence
{
get
{
if (_PacketsSequence == null)
_PacketsSequence = new List<Packet>();
return _PacketsSequence;
}
set { _PacketsSequence = value; }
}
}
then create the class
public class PacketParser
{
private List<Session> _TermonatedSessions;
private IList<Session> _Sessions;
private IDictionary<int, List<Packet>> _Buffer;
public PacketParser()
{
_TermonatedSessions = new List<Session>();
_Sessions = new List<Session>();
_Buffer = new Dictionary<int, List<Packet>>();
}
public void ParsePacket(string filePath)
{
OfflinePacketDevice selectedDevice = new OfflinePacketDevice(filePath);
using (PacketCommunicator communicator = selectedDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
try
{
communicator.ReceivePackets(0, AnalyzeCurrentPacket);
}
catch { }
}
var AnalyzedSession = CombineOpenCloseSessions();
}
private IList<Session> CombineOpenCloseSessions()
{
_TermonatedSessions.AddRange(_Sessions);
_Sessions.Clear();
_Buffer.Clear();
return _TermonatedSessions;
}
}
I've got a server and client set up using TcpListener and TcpClient.
I want to send an object to my server application for processing.
I've discovered the using System.Runtime.Serialization and the following documentation, but I didn't want to faff around to find that I'm doing it in long winded way.
The question: What is the best way to process and send an object over the TCP stream?
Sending and receiving.
Here's an example of my object:
// Create a new house to send
house newHouse = new house();
// Set variables
newHouse.street = "Mill Lane";
newHouse.postcode = "LO1 BT5";
newHouse.house_number = 11;
newHouse.house_id = 1;
newHouse.house_town = "London";
Assuming you have a class House (available on both sides of your connection) looking like this:
[Serializable]
public class House
{
public string Street { get; set; }
public string ZipCode { get; set; }
public int Number { get; set; }
public int Id { get; set; }
public string Town { get; set; }
}
You can serialize the class into a MemoryStream. You can then use in your TcpClient connection like this:
// Create a new house to send house and set values.
var newHouse = new House
{
Street = "Mill Lane",
ZipCode = "LO1 BT5",
Number = 11,
Id = 1,
Town = "London"
};
var xmlSerializer = new XmlSerializer(typeof(House));
var networkStream = tcpClient.GetStream();
if (networkStream.CanWrite)
{
xmlSerializer.Serialize(networkStream, newHouse);
}
Of course you have to do a little more investigation to make the program running without exception. (e.g. Check memoryStream.Length not to be greater than an int, a.s.o.), but I hope I gave you the right suggestions to help you on your way ;-)
First create a empty ServerApplication and ClientApplication as Console Application to simplify the example.
Then, put the definition for the serializable object into a separate assembly and then add a reference to the shared assembly to each project (server and client). Is necesary share the same object, not just an identical class copy.
To Generate DLL >
Right clic in Solution 'ServerApplication' in the Solution Explorer > Add New Project... -> select Class Library
(e.g. name this project MySharedHouse)
Rename the default Class1 to House and complete it
[Serializable]
public class House
{
public string Street { get; set; }
public string ZipCode { get; set; }
public int Number { get; set; }
public int Id { get; set; }
public string Town { get; set; }
}
Right clic in MySharedHouse and Build.
Now the dll is build and we need to add it in Server Project and Client Project.
Right clic in ServerApplication > Add Reference > Browse and find the dll, for this example
Projects\ServerApplication\MySharedHouse\bin\Debug\MySharedHouse.dll
Repeat the process in ClientApplication using the same dll (same path).
Now you can use instances of House class in ServerApplication and ClientApplication as a single object, simply adding the sentence "using MySharedHouse" at the top.
SERVER CODE
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using MySharedHouse;
namespace ServerApplication
{
class Program
{
static void Main(string[] args)
{
MessageServer s = new MessageServer(515);
s.Start();
}
}
public class MessageServer
{
private int _port;
private TcpListener _tcpListener;
private bool _running;
private TcpClient connectedTcpClient;
private BinaryFormatter _bFormatter;
private Thread _connectionThread;
public MessageServer(int port)
{
this._port = port;
this._tcpListener = new TcpListener(IPAddress.Loopback, port);
this._bFormatter = new BinaryFormatter();
}
public void Start()
{
if (!_running)
{
this._tcpListener.Start();
Console.WriteLine("Waiting for a connection... ");
this._running = true;
this._connectionThread = new Thread
(new ThreadStart(ListenForClientConnections));
this._connectionThread.Start();
}
}
public void Stop()
{
if (this._running)
{
this._tcpListener.Stop();
this._running = false;
}
}
private void ListenForClientConnections()
{
while (this._running)
{
this.connectedTcpClient = this._tcpListener.AcceptTcpClient();
Console.WriteLine("Connected!");
House house = new House();
house.Street = "Evergreen Terrace";
house.ZipCode = "71474";
house.Number = 742;
house.Id = 34527;
house.Town = "Springfield";
_bFormatter.Serialize(this.connectedTcpClient.GetStream(), house);
Console.WriteLine("send House!");
}
}
}
}
CLIENT CODE
using System;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using MySharedHouse;
namespace ClientApplication
{
class Program
{
static void Main(string[] args)
{
MessageClient client = new MessageClient(515);
client.StartListening();
}
}
public class MessageClient
{
private int _port;
private TcpClient _tcpClient;
private BinaryFormatter _bFormatter;
private Thread _listenThread;
private bool _running;
private House house;
public MessageClient(int port)
{
this._port = port;
this._tcpClient = new TcpClient("127.0.0.1", port);
this._bFormatter = new BinaryFormatter();
this._running = false;
}
public void StartListening()
{
lock (this)
{
if (!_running)
{
this._running = true;
this._listenThread = new Thread
(new ThreadStart(ListenForMessage));
this._listenThread.Start();
}
else
{
this._running = true;
this._listenThread = new Thread
(new ThreadStart(ListenForMessage));
this._listenThread.Start();
}
}
}
private void ListenForMessage()
{
Console.WriteLine("Reading...");
try
{
while (this._running)
{
this.house = (House)this._bFormatter.Deserialize(this._tcpClient.GetStream());
Console.WriteLine(this.house.Street);
Console.WriteLine(this.house.ZipCode);
Console.WriteLine(this.house.Number);
Console.WriteLine(this.house.Id);
Console.WriteLine(this.house.Town);
}
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
}
Wooala! the first house to be sent over TCP/IP
You can simply decorate your House class with the [Serializable] attribute. (You do not need to define all the other stuff as posted in the other answer)
You can then send this object on the wire by serializing it using the BinaryFormatter class.
Have you considered setting up a WCF service instead of using TcpListener and TcpClient ? Makes life a lot easier.
For instance you could define a service that returned a house
[ServiceContract]
public interface IService
{
[OperationContract]
House GetHouse(int houseId);
}
See this real world example.
Your answer implies the following object (it is common practice to name classes using PascalCase):
[Serializable]
class House:ISerializable
{
public string Street {get; set;}
public string PostalCode {get; set;}
public int HouseNumber {get; set;}
public int HouseID {get; set;}
public string City {get; set;}
public House() { }
protected House(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new System.ArgumentNullException("info");
Street = (string)info.GetValue("Street ", typeof(string));
PostalCode = (string)info.GetValue("PostalCode", typeof(string));
HouseNumber = (int)info.GetValue("HouseNumber", typeof(int));
HouseID = (int)info.GetValue("HouseID", typeof(int));
City = (string)info.GetValue("City", typeof(string));
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand,
Flags=SecurityPermissionFlag.SerializationFormatter)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new System.ArgumentNullException("info");
info.AddValue("Street ", Street);
info.AddValue("PostalCode", PostalCode);
info.AddValue("HouseNumber", HouseNumber);
info.AddValue("HouseID", HouseID );
info.AddValue("City", City);
}
}
Now you can serialize your objects:
void Send(Stream stream)
{
BinaryFormatter binaryFmt = new BinaryFormatter();
House h = new House()
{
Street = "Mill Lane",
PostalCode = "LO1 BT5",
HouseNumber = 11,
HouseID = 1,
City = "London"
};
binaryFmt.Serialize(stream, h);
}
How would you deserialize the xml House stream back to a House object on the receiving end?
I'm refering to the solution given in Fischermaen's answer.
On my recieving end I can see a string representation in my Output window by using the following:
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
Thank you in advance.
EDIT *
Ok well this solution has worked for me. Might need some tidying up.
Here's a method to deserialize a string:
public static T DeserializeFromXml<T>(string xml)
{
T result;
XmlSerializer ser = new XmlSerializer(typeof(T));
using (TextReader tr = new StringReader(xml))
{
result = (T)ser.Deserialize(tr);
}
return result;
}
Then from my TPC/IP Recieving end I call the method like so:
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
House house = DeserializeFromXml<House>(encoder.GetString(message, 0, bytesRead));
//Send Message Back
byte[] buffer = encoder.GetBytes("Hello Client - " + DateTime.Now.ToLongTimeString());
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
tcpClient.Close();
}