Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I a very new to C#, so please be aware of that. Currently I am writing a program where a server sends messages to me, that are in format of JSON-strings. How can I read a string from the inputstream of that socket?
You can deserialize JSON-Strings into the proper object with the newtonsoft
You can get a socket as a Stream (for use with most common serializers) by using NetworkStream; however, there is a very important thing to consider: "framing". Since you say "messages" (rather than "message"), it sounds like multiple payloads will be sent on the same socket. TCP just represents an ordered byte-stream; if you're sending one message, this is easy - just pass the NetworkStream to your chosen deserializer, and: job done. But not so easy if you want to transfer multiple payloads over a single connection, since the two ends need to agree on how to know where each payload starts and ends, which is "framing". For text protocols, a common framing mechanism might be to terminate each payload with a sentinel such as a line-end (some combination of CR/LF), or a nul character (byte zero). For binary protocols, this commonly means using a length prefix (in an agreed format) before each message. Unfortunately, in both cases you usually need to buffer the stream until you have a complete payload (noting that you might end up with "a payload and a bit of the next payload" or similar), and use a MemoryStream (or similar) on each buffered frame in turn.
Note that you can also use StreamReader to access a Stream in terms of string via an Encoding; this may be useful if your deserializer takes TextReader or string.
More recently, the "pipelines" API can replace the Stream metaphor, but a: not all serializers support "pipelines" yet, and b: it is quite an advanced topic, so probably not great for "very new to C#" reasons; but if you're interested, I have a multi-part blog series here.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've searched over 2 weeks for samples or anything else for my question.
Found some topics and examples but can't use them ...
Here is the problem : I have a server-client application which the server have to listen all the time and client is sending continuously Images to the server.
I've done the send-and-done which means client send 1 image to the server and server receive the image and socket will be closed .
But i want to send continuously Images to the server ...
Found this question : Can a TCP c# client receive and send continuously/consecutively without sleep?
But can't use them and samples .
I know the basic TCP Socket Programming and Basics of Thread Programming , but can't implement this .
Sorry For my bad english !
=====edit
actually a timer captured a screenshot with 1 second interval and these captured images after a process for compressing are send to server .
its continuously sending (Just Sending).
Is there any sample or something that i can use ?
Thanks .
When sending a single message on a socket, you can just send the payload and close - and the receiver just has to read until the socket reports it has closed and they'll have the message; nice and simple, but it doesn't scale to multiple messages.
You can't just use the packet layout because TCP is implemented as a stream protocol not a packet protocol; how you receive the data does not need to match (in terms of packets) how it is sent.
Thus, to send multiple messages on a TCP socket you need to implement some kind of framing mechanism. Any number of framing mechanism are available. A very simple mechanism might be to send a sequence of:
length (4 bytes, little-endian 32-bit integer)
payload ({length} bytes)
length (4 bytes, little-endian 32-bit integer)
payload ({length} bytes)
length (4 bytes, little-endian 32-bit integer)
payload ({length} bytes)
length (4 bytes, little-endian 32-bit integer)
payload ({length} bytes)
And similarly the recipient would buffer 4 bytes, interpret the length, then read that many bytes as a frame; rinse, repeat.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is my problem :
I'm used to receive data like int, char* & cie... throught a TCP socket in c/c++, but how to manage that in c#? I will communicate with a c++ server, sending me int, bools and char*. I think my bigger problem come from the fact than a char in c# = 2bytes ...
Thanks a lot, and sorry for my poor english :/
Firstly, I really hope you aren't actually sending a char*, as that makes zero sense outside of a given process, and isn't even a well-defined length.
Basically, you need to sit down and write down the encoding rules for all the things you are sending. For example, you might say:
int is 4 bytes little-endian
text is utf-8 encoded with a length-prefix (bytes, not characters) as an int
a bool is a single byte (to avoid boundary issues)
etc for every data type you need
Then figure out how you are going to partition multiple fields of a single message, and how you are going to frame multiple messages in the same socket.
Or perhaps a better option is to choose one of the many pre-existing serialization formats and offload the thinking to that. If you are after efficiency, then "protocol buffers" would be an excellent choice. If you want simplicity maybe JSON.
If you still want to hand-code it, then : start by writing down what exactly it is going to look like on the wire, then implement that.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
How to encrypt Decrypt text without using Base64String?
I don't want to use Base64String because encrypted text should not contains any special character like #, $, #, /, \, |,=,% ,^
Well the obvious approach if you don't want to use base64 is to use base16 - i.e. hex.
There are plenty of examples of converting between a byte array and a hex string representation on Stack Overflow. (BitConverter.ToString(data).Replace("-", "") is an inefficient way of performing the conversion to a string; there's nothing quite as simple for the reverse, but it's not much code.)
EDIT: As noted in comments, SoapHexBinary has a simple way of doing this. You may wish to wrap the use of that class in a less SOAP-specific type, of course :)
Of course that will use rather more space than base64. One alternative is to use base64, but using a different set of characters: find 65 characters you can use (the 65th is for padding) and encode it that way. (You may find there's a base64 library available which allows you to specify the characters to use, but if not it's pretty easy to write.)
Do not try to just use a normal Encoding - it's not appropriate for data which isn't fundamentally text.
EDIT: As noted in comments, you can use base32 as well. That can be case-insensitive (potentially handy) and you can avoid I/1 and O/0 for added clarity. It's harder to code and debug though.
There's a great example in the MySQL Connector source code for the ASP.NET membership provider implementation. It may be a little hassle to download and research, but it has a well-established encryption and decryption module in there.
http://dev.mysql.com/downloads/connector/net/#downloads
Choose the 'source code' option before downloading.
If you want encoding/decoding for data transmission or condensed character storage, you should edit your question. Answers given to an encoding question will be much different than answers given to an encryption/decryption question.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm writing a library and instead of returning a byte array from an EventArgs derivation, it says I should return something like IList or ReadOnlyCollection instead.
Normally I'd be all for this but most of the existing .NET Framework uses byte arrays as opposed to generic list interfaces.
So if I were to use IList then when accessing the eventargs, if a client wanted to call File.WriteAllBytes he or she would have to do using System.Linq; and call the ToArray extension method to get the IList in the form of an array of bytes. Of course there are other ways to do this but this is the most elegant and typical.
Clients of this library are always going to want things to be in terms of an array of bytes so that they interface nicely with the rest of the framework.
Also, optimization may come in to play here. There is potential for large amounts of bytes to be manipulated so having to recopy the entire list just to get it in the form of a byte array each time would likely slow things down.
Lastly, it's just plain unpleasant. If clients are always going to want a byte array, then why not just give it to them? Do framework design guidelines not apply in this situation? What would you do?
There is potential for large amounts of bytes to be manipulated so having to recopy the entire list just to get it in the form of a byte array each time would likely slow things down.
But that is precisely why it should not be a byte array. Suppose you do this:
byte[] x1 = GetByteArray();
x1[0] = 0;
byte[] x2 = GetByteArray();
Every time you call GetByteArray you have to create a new byte array. Why? Because someone might have changed the one you handed out last time to have different contents! By handing out a byte array you guarantee that you are going to have to reconstruct that byte array from scratch every single time.
By contrast, if you hand out a read only collection of bytes then you can hand out the same collection over and over again. You know it is not going to change.
Clients of this library are always going to want things to be in terms
of an array of bytes so that they interface nicely with the rest of
the framework.
There you have your answer - FxCop output is in most cases just helpful suggestions - not commands - if this particular one doesn't apply to you you can even turn it off.
The guidelines and recommendations offered by FxCop are not always applicable in every situation. You don't need to follow them, and in some situations you shouldn't.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have a scenario where I want to clearly convey that it's the caller's responsibility for disposing a stream while at the same time preventing the caller from discovering the underlying file's path -- the caller shouldn't know that the stream came from the file system. Also, the caller isn't going to need the stream until later on, so I probably don't need to open it immediately.
Given that, I thought that it might be a good idea to leverage Lazy<T> for this purpose, as in:
public Lazy<Stream> GetContent(string key)
{
string path = GetFilePath(key);
return new Lazy(() => File.OpenRead(path));
}
Am I over-thinking this? Should I just return a Stream instead?
Be aware that returning Lazy<T> in this way means that if multiple pieces of code re-use the same lazy "factory" then they will get exactly the same stream. For example, if one piece of code disposes the stream then the others will be attempting to use the same disposed stream etc.
If you really need to defer creation of the stream then I'd suggest returning a Func<T> instead. This will allow the returned delegate to be safely shared and re-used, creating a new stream instance each time it is invoked.
My own preference would probably be to just return a plain Stream, and document very clearly that it's the caller's responsibility to handle the disposal.
Lazy<> is the exact opposite, it is a creation detail, not a destruction detail. Furthermore, the client has no decent reason to delay construction when interested in the content. These are just wrong signals, return a Stream.
the caller shouldn't know that the stream came from the file system
Caller may cast GetContent(key).Value to FileStream. You may want to decorate it with something if the need is not to expose FileStream.
Anyway personally I don't see any advantages of using Lazy here.