C# is there an easy way to get into TCP Socket Programming? - c#

I've worked on a program that uses databases to send small messages from one PC to another. What I've done is put the database in a shared folder, have the program on the other PC connect to it (via a Path, no less), and there it is, a simple and easy way to get messages to and fro PCs on a network. Not the best option, but it's just homework, and the quick and dirty approach got me a grade.
But now the homework is done, and I'd like to improve upon what I did. The problem with the program is in the deployment stage. There are too many folders / installation paths and administrative / sharing issues regarding pathing directly to a database on a shared folder.
So the good folks here in stackoverflow advised me to try Socket Programming, which I think is a bit out of my league. But you never know...
Also, I'm aware of the difference between Sync and Async socket programming. One blocks, the other doesn't. The program I'm working on is a simple turn-based game, so I thought Synchronous might be good enough, since if it's not your turn, you really can't do anything. The issue however is that the program is treated as "not responding". I tried asynchronous, but ran into problems with threading, something I consider WAY out of my league.
Logically, the program is simple. One host, one client. Upon client connection, host sends data. Then client receives, send out its own data. And so on, until one player loses.
I'm sorry to say only .NET 2.0 is installed in my school. No WCF or anything. Also, it must be done in C# Windows Forms, so XNA is out.
So, I'd like to ask... is there an easy way to get into Socket Programming? Any guides / sample projects that can help? Pre-made codes that can be studied, and adapted?
Majority of the samples I found and adapted are chat applications, which I thought good enough, but making it modular simply breaks it.

The chat application examples you encountered should be enough. It is not clear to me what you refer to as "making it modular".
What you need is to design a protocol to be sent over the connection, an agreement of rules so to say, so that one knows what the other is talking about. So instead of sending plain text (chat) you can send the following:
0x03 (length of the message)
0x0A (move command in this fictional protocol)
0x02 (parameter 1 of the command, X coordinate in this case, it's all defined in the protocol design)
0x05 (parameter 2 of the command, Y coordinate in this case, it's all defined in the protocol design)
Now it's entirely up to you what happens after you received and interpreted the data. Personally I would go for the Async solution, since it leaves your program to do other stuff (graphics?). And it's more easily adaptable in code, in my experience.

I've made some classes which can be used to transport objects over a socket using the BinaryFormatter.
Here are some tests for my BinaryTransport class:
http://fadd.codeplex.com/SourceControl/changeset/view/67972#1055425
The actual class:
http://fadd.codeplex.com/SourceControl/changeset/view/67972#1054822
Do note that it's a while ago that I wrote them. I just noticed some small bugs. But either use them or just study the classes to learn more.

I remember when I started with socket communication in C# I tried to implement a simple chat program between a client and a server and then between multiple clients. Here is the tutorial that I was reading then: http://www.codeproject.com/KB/IP/TCPIPChat.aspx
If you want the full code I can upload my final project and you can study the code. It also uses multithreading so you can see how to handle this situation in GUI applications.
Side note: Wow, that database idea is the craziest thing I've seen in terms of PC-to-PC communication. Well done!

One interesting, useful and easy exercise you can do to learn about sockets (which C# makes it easier even) was creating a TCP-based logger.
During development every programmer needs a way to know what's happening under the hood at certain points. Without a logger you would normally write something like:
Console.WriteLine( "blah" );
which results in a dull, unfiltered, unorganized string thrown to the output window.
I created a TCP-based logger very easily using sockets. In one hand you have a separate Winforms application (the server), which is in charge of listening to incoming messages and beautifully displaying them on a rich-content control. In the other hand, you write a very simple class (the client) with a single function like:
public static class MyConsole
{
public static void WriteLine( string message, string whatever )
{
// send to the net
if( mTcpSocket.Connected )
mTcpSocket.Send( message );
// in case the server is not there we still have regular output
Console.WriteLine( message );
}
}
I created this logger once and have been using it ever since. Furthermore, given its tcp nature, with minor changes on the server side I've been successfully using it from different languages, as C# and Java, and now using it from ActionScript.

Related

Communication between two c# applications

I have a problem, have not much experience in C #, so I did a lot of research and I'm stuck.
I have to make two applications C #, the first applications is windows forms, the second runs in the background, so that the first applications will be a (POS) sales point that need to communicate with the application background for information as (products, customers, etc ...) and send data, so do not want to use web service for problems like timeouts, so anyone can help me with some idea to perform this task?
it is important to mention that the application in background will be just one while the POS applcations wich will communicate with it will be a lot (n number of apps).
There is a myriad of ways of doing interprocess communication. As the question is so generic, I will point out some more common ways.
The background process can be a windows service which updates the DB and POS systems query the DB to retrieve what they need. Even if the background process reads from the same DB, you can have a separate table which has "finished" information ready for the POS piece to pick up. Now you can use a file instead of a DB to store this finished results too, but most folks prefer DB.
You can use WCF channel to establish communication between the POS piece and the background process.
You can convert your background process to a web-service and let your POS piece communicate using XML. I don't think any time-out issue should be a problem. You will have to explain better what time-out issue causes you to not use this option.
You can convert the whole piece into a web-site and the POS will simply be a browser then
You can use a bus like Tibco or MQ to pass data.
Or you can go the old fashioned way of TCP sockets.
The most preferred way is usually the web-servcie or web-site way depending on your constraints.
Typically you'll use a message queue for something like this. They are a component in ensuring clean separation of concerns reducing and cross-application coupling and are meant to receive messages by some publisher (thus freeing the publisher of any further responsibility), and pushing messages to some subscriber.
RabbitMQ is a popular framework: https://www.rabbitmq.com/
(note that RabbitMQ (and other ready-built frameworks) can sometimes be daunting for new application programmers as they handle a great many use cases. However the underlying concept of writing to a queue from one application and reading from the queue in the other application is really the key here... feel free to implement a small utility of your own as a learning experience, but I do recommend an pre-existing framework if you're comfortable using such)
One method is to use named pipes for such communications between different programs.
How to: Use Named Pipes for Network Interprocess Communication
If you do not want to use web service (based on soap protocol),
you could attempt to use web api. In this way, you could build rest based interfaces with json (json streaming between computers is faster than xml streaming).
I think the following link can be usefull to you:
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/using-web-api-with-aspnet-web-forms

Very simple Client/Server Message networking in C# (.NET and Xamarin/Mono)

I would like to write a simple application to send text messages between a server (Windows) and a client (a Xamarin App running on android), which would remotely control music (played by the server) with basic text commands (like "pause", "skip", "play " ...).
The setup I had tought about would work like this:
When I start the android app, it tries to connect to the server (they are in the same local network using LAN/WiFi, so I'd just use my local IP for that). Then, with the connection established, both would be able to send messages to the other one (client -> server: play this song etc, server -> client: song finished, song not found, etc). Of course, that should be done in a threaded or asynchronous manner so that both applications do not block up their UI. The server would run in the background and wait for the next message, which would trigger an event taking care of doing the requested action.
I already searched on how to do this in a beginner friendly way, but haven't found much that I could work with. I only have basic knowledge on asynchronous/threaded programming, and not enough on networking (in .net). Each solution I found wasn't made for a connection to stay open but rather "read stream, send answer, close connection" (which is not what I want) or was far to complex.
I know that there are countless tutorials available, but I simply couldn't make up how to use them for my scenario. Example Code or easy to understand explanations on how to accomplish things like keeping the connection open in a non-blocking way, and how to send and receive a complete, self-contained message, because I can't quite wrap my head around that (if I just read a fixed size of bytes, how can I be sure to get exactly one message ?).
So, I'd be grateful for every tip showing me in the right direction, like for example which of the many classes would be best to use for this (there seems to be an awful lot of them, without notion which is suited for what). I apologize if this question seems rather dumb, but I'm an absolute beginner in this. Thank you very much in advance !
Figured it out myself, after some more research. System.Net.Sockets.UdpClient is working like a charm, and, more importantly, available and working on both platforms I want to target, so I will just go with it.

socket for messaging between UI and C code?

I have implemented a C library and would like to expose its functionality to a UI. The UI will either be a Windows Forms UI or a WPF UI.
To come up with a more "platform independent" way of tying the UI and the C lib together, I have thought about creating a socket on the UI side as well as on the C-side. The socket will be used for exchanging bi-directional messages between the UI and the library. I know that there might be some overhead to doing it in this way, but the "message traffic" between the UI and the C code is not going to be heavy.
Another reason for doing it this way, is because I've read that there are so many pitfalls that you have to be aware of when you use PInvoke, IJW, COM or CLI (for enabling C#-to-C calls and C-to-C# calls). This socket-approach makes it more clean and I'll have better control of what's actually going on when the C# code sends a message to the C code (or the other way around).
To get started and to avoid wasting my time, I'm looking for some advice from seasoned developers who know a lot about socket code.
I'm not sure about what the requirements for the socket code on either side should be? I do know that I want any component on the UI side to be able to send and respond to messages.
Using sockets will require your c program to become a server, which opens a socket and listens. Upon receiving a request it does some stuff and typically returns an answer. The idea is communication between networked computers.
here is a basic example. http://www.linuxhowtos.org/C_C++/socket.htm
Writing socket code requires compatable data formats between the sending app and receiving app. This means you need to carefully structure your messages and ensure that each integer, long integer, float, double and fixed length string exactly match. An extra byte on 1 side will scramble your message into junk. If your c and c# data encoding formats mismatch - you will have extra decoding/formatting work.
I preferred to use ONC-RPC to write client server code between inequal systems. A decade ago I used RPC to connect big endian Solaris to a little endian VMS system - it worked flawlessly, it was really quick to write.
I'd avoid writing low level socket code because it's time consuming and difficult, except when you need high performance networked apps.

Get a variable from one program into another

Im not even sure how to ask this question, but i'll give it a shot.
I have a program in c# which reads in values from sensors on a manufacturing line that are indicative of the line health. These values update every 500 milisecconds. I have four lines that this is done for. I would like to write a "overview" program which will be able to access these values over the network to give a good summary on how the factory is doing. My question is how do I get the values from the c# programs on the line to the c# overview program realtime?
If my question doesnt make much sense, let me know and I'll try to rephrase it.
Thanks!
You have several options:
MSMQ
Write the messages in MSMQ (Microsoft Message Queuing). This is an (optionally) persistent and fast store for transporting messages between machines.
Since you say that you need the messages in the other app in near realtime, then it makes sense to use MSMQ because you do not want to write logic in that app for handling large amounts of incoming messages.
Keep the MSMQ in the middle and take out what you need and most importantly when you can.
WCF
The other app could expose a WCF service which can be called by your realtime app each time there's data available. The endpoint could be over net.tcp, meaning low overhead, especially if you send small messages.
Other options include what has been said before: database, file, etc. So you can make your choice between a wide variety of options.
It depends on a number of things, I would say. First of all, is it just the last value of each line that is interesting for the 'overview' application or do you need multiple values to determine line health or do you perhaps want to have a history of values?
If you're only interested in the last value, I would directly communicate this value to the overview app. As suggested by others, you have numerous possibilities here:
Raw TCP using TcpClient (may be a bit too low-level).
Expose a http endpoint on the overview application (maybe it's a web application) and post new values to this endpoint.
Use WCF to expose some endpoint (named pipes, net.tcp, http, etc.) on the overview application and call this endpoint from each client application.
Use MSMQ to have each client enqueue messages that are then picked up by the overview app (also directly supported by WCF).
If you need some history of values or you need multiple values to determine line health, I would go with a database solution. Then again you have to choose: does each client write to the database or does each client post to the overview app (using any of the communication means described above) and does the overview app write to the database.
Without knowing any more constraints for your situation, it's hard to decide between any of these.
You can use named pipes (see http://msdn.microsoft.com/en-us/library/bb546085.aspx) to have a fast way to communicate between two processes.
A database. Put your values into a database and the other app then pulls them out that same database. This is a very common solution to this problem and opens up worlds of new scenarios.
see: Relation database

Patterns for Multithreaded Network Server in C#

Are there any templates/patterns/guides I can follow for designing a multithreaded server? I can't find anything terribly useful online through my google searches.
My program will start a thread to listen for connections using TcpListener.
Every client connection will be handled by it's own IClientHandler thread. The server will wrap the clientHandler.HandleClient in a delegate, call BeginInvoke, and then quit caring about it.
I also need to be able to cleanly shutdown the listening thread, which is something I'm not finding a lot of exampes of online.
I'm assuming some mix of lock/AutoResetEvents/threading magic combined with the async BeginAceptTcpClient and EndAcceptTcpClient will get me there, but when it comes to networking code, to me it's all been done. So I have to believe there's just some pattern out there I can follow and not get totally confused by the myriad multithreaded corner cases I can never seem to get perfect.
Thanks.
Oddly enough you may find something on a Computer Science Assignment, CSC 512 Programming Assignment 4: Multi-Threaded Server With Patterns. Altough it's C++ voodoo but the theory is quite understandable for someone who can do C#.
Acceptor/ Connector
Monitor Object
Thread Safe Interface
Wrapper Facade
Scoped Locking
Strategized Locking
Reactor
Half Sync/Half-Async
Leaders/Followers
Altough you can get the whole list of nice readings on the main page.
Take a look at this previous question:
How do you minimize the number of threads used in a tcp server application?
It's not strictly C# specific, but it has some good advice.

Categories