I am writing a chat program between a server and a client in C# .Net. Both users, aside from chatting can engage in different activities like remote desktop and playing games together.
I have a few questions:
Multiple threads will be sending and receiving stuff from the client at the same time, that means every option need to identify which packet is meant for him and take data from it ? (Running a remote desktop while transferring a file a same time, the remote desktop thread will see the file packets arriving at stream but should ignore it, right?)
What's a good buffer size to set for the socket I will accept clients in?
Do I communicate in form of specialized class containing the data or try to keep the communication as a byte array I send over the stream?
The questions 2 and 3 are impossible for us to answer because we don't know what the communication and the requirements look like.
As for handling multiple threads: that is hard to get right, I'd use an existing solution.
I suggest you have a look at 0MQ as it might prevent you from reinventing the wheel.
There are .NET client libraries available: http://nzmq.codeplex.com/ and a nuget package http://www.nuget.org/packages/clrzmq/2.2.5 as well.
A good start is The Guide
For a quick example see this C# server and its hello world client in C#
Related
I have created an asp.net website. On that website the user can create webpages and put buttons. These buttons sends commands via web socket to a tray application I implemented. The tray application then takes the commands and passes them along to various third-party applications using TCP connections. the third-party applications then perform the commands and send back their status to the tray application. The tray application writes the status into an sql database. The website reads the status from the database and processes the status (for example, it highlights the button that send the original command)
Right now it is a mess. For example the third-party applications all handle the communication in different ways. How would I best go about organizing such an application?
I use ab sql database in between because I cannot be sure that the user wont reload the website. And then what happens to the web socket? Also, it can update its buttons on its own pace. Is that a good solution?
Also, my knowledge of TCP and socket programming is sorely lacking. Most resources, tutorials, guides just give really simple examples. Isn't there something better out there? (books, articles)
I am using a TCPListener that accepts the website requests in an infinite loop:
static void TcpListenerWorker_DoWork(object sender, DoWorkEventArgs e)
{
server = new TcpListener(IPAddress.Parse(Properties.Settings.Default.TrayAppServer), Properties.Settings.Default.TrayAppPort);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
if (TcpListenerWorker.CancellationPending)
break;
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
...
Is there a better way to link the tray application to the website?
The tray application also has to check if the third-party application is running. Only if it is running, should the socket be created. If the third-party application crashes to connection is gone. How do I reestablish the connection properly?
The user should now if he can send commands. For that I check if the application is running like so
Process.GetProcessesByName("exApp1");
Is there a better way to check for the applications? Maybe by trying to establish a tcp connection and if it fails, the app is not running. But relying on a failed connection attempt might not be good decision.
A lot of errors occur. Connections disappear, commands do not arrive. Are there APIs I could use to handle these things better (better error and exception handling)?
Sorry, if all that sounds confusing. The entire project is a mess. Please tell me if I should explain more.
One thing I would do is sit back and unravel the spaghetti in your mind first. The fact ech uses a different means of communication should not matter if you have properly abstracted them.
The first question is "Do you need TCP socket level communication?" I see nothing that screams "yes" here. Assuming you do, your first issue is getting the socket communication. Get that up and running first. If this is multiple clients, there are open source projects you can start with to handle the communication bits. As an example, there is a project called Socket Server on CodePlex that can manage the sockets. I am, personally, not fond of the way the project is set up, but follow the documentation and get a server up. Or search for another piece that can do this for you.
Your next problem is "should I set up a socket?". If I am right, this sounds like a client side issue; if so, solve it separate from the socket connection and be done with it. I don't have bandwidth to determine if your method is the best here, but encapsulate that code and you can swap out the method of determining if the app is running later.
Now let's jump down to multiple apps communicate differently. If you have one in to multiple outs, think about a simplified service bus and then write adapters for the applications that need to listen. If it is multiple in to one out, then you need to write an adapter for the application anyway. Perhaps some apps do require socket level communication, and you need a socket to web API adapter (just an example, as I don't have enough detail).
The core of the advice is break the problem down and see what you can separate out and focus on. Many simple problems are generally easier to solve than one big complex problem.
I'm trying to do some research on tcp client and tcp listener in c# for a microsoft exam. I've found quite a lot on the internet about how to use them, but very little about why I should use them.
I've discovered that it's a secure way of communicating between 2 applications, but I don't get why I should use tcp instead of (for example) just exposing a method on one application and calling it from the other.
Does anyone know of any good webpages that might be able to explain this to me?
If you are intending to communicate between applications with in a system you can use any inter process communication methods. But if you intend to have two applications running in different machines than you need a mechanism outside of IPC. This is where TCP and UDP come into picture.
TCP/UDP are elaborate protocols(rules) that govern how the two applications connect, exchange data and terminate the connection. (UDP , does not have the connect/terminating phase, BTW.)
Its interesting. Start with Wiki.
Most start socket programming with this well known page (In 'C' though) - http://beej.us/guide/bgnet/
I have the same dilemma as the one who posted this topic, Real-time communication with WCF
except that my problem is not about games programming. I would like to know what's the best method to use to be able to have a real time communication in between two windows applications (server-client). I am using visual c++/c# to date and i would like to be able to display all the Feeds that are being received by my server to the client in real time.
I have started trying to use .NET remoting but in my continuous research, it appears that it will use SOAP-http, and might affect the speed of the communication. My server and client will communicate using the internet and .NET remoting does not permit the use of TCP Channel when communicating in between a firewall or the internet.
Your inputs will be greatly appreciated.
I guess it depends on your escenario, if you want "real-time" and you are willing to lose some packages in the process you are better with UDP, take a video conferencing tool for example, by the time you recover your slow packages you will have to move and display the next frame in the video or audio; that is a good example for the use of UDP. This is the reason why UDP is much faster than TCP.
If however, you are not willing to lose a single bit of your message, then TCP was made for you because if you lost a package the protocol will request it again to have your complete message as complete as possible.
Additionally it depends on the way the communication is being sustained, is the information flowing from one to many?, from many to many?, one to tone?
Take NetNamedPipeBinding for instance, this will be much faster process, but is only deployed in a single machine but accross processes. Whereas NetMsmqBinding will help you to build queues and it will be amazingly reliable and scalable for scenarios where your load will be a massive number of connections.
In the end, it all boils down to your concrete escenario and your business goals.
Hope it helps
If you are willing to do your own message parsing, you can use standard TCP sockets with the TcpClient and TcpListener classes. If your data is already a serializable object, you could serialize it into a text stream and just send it over the socket, deserializing it on the client side.
To get it to work over the internet, the server needs to have the port forwarded on your router, the client would just attach to the server's public IP. You would obviously need to add an exception in your firewall for this port as well.
The biggest problem with WCF and large data is setting up the streaming, by default WCF sends everything at once, which isn't practical for large files.
I am currently new to C# and I need to understand simple server-client architecture!
I am currently trying to write a simple server/client program where basically a client can send a variable to a server and the server can send it to another client. Problem is that I am really blind to this as I am still very new to C# although I have some experience with Java (But still not with networking).
My question is:
How many files will i Have to write?
Can anybody be nice enough to provide me with a framework or example for a program like this?
What is a TCP server?
This is intended to be for an online game. One client will roll the dice and the server must show all the other clients that this is the value the first client rolled.
Any help would be greatly appreciated!
Answer to all of your questions: MSDN - Network Programming (.NET 4)
Since you are planning on TCP (because you want state) you need to develop a strategy. You'll get plenty of information about establishing a connection and moving some sort of data back and forth. Google will give you more than you can handle. Without doing all the work, here are a few steps to get you oriented.
1) Connection Registration - When a client comes online and wants to communicate with the server it first needs to say "Hey I'm here and want to role some dice." This initial handshake could be a connection id that is used for a heart beat and/or transactions. The server will use this to identify data and the respective thread if open.
2) Heart Beat - Now that the client has registered with the server the client is responsible for providing a heart beat saying it's still there and still planning to continue work. Typically every 3 - 10 seconds is good.
3) Develop the Request/Response protocol - For "every command" there will be a formal process. This formal process will include the connection id but also a request id. The client will not accept a response unless it receives the corresponding request id. Furthermore, every request will require a success or fail response to identify if it conforms to the API or what not. Within the request will be the command or action to perform. Some people use int's to dispatch a command id then use a switch on the id to call an entry-point method (cmd id = 1 is connect(), cmd id = 2 is rolldice(), etc). You might include additional payload that identifies the result from the command.
In short, 1 is the handshake, 2 is the keep-alive and 3 is passing data back and forth.
Now whether to use socket or WCF, I'd recommend to have a basic understanding of TcpClient programming then run with WCF. You'll be amazed how simple socket programming is but the overhead is a killer. Nothing to be intimidated by. It's a lot of work to coordinate calls, threads and not to mention security. WCF on the other hand does shave some of this overhead off.
I'd check out this question...
How to use socket based client with WCF (net.tcp) service?
1) The number of files will depend on your particular implementation. You can create this architecture as simply as 1 class for the server and 1 class for the client (you can have more than one class in a file). Depending on the complexity and choices you make during the design you could have many files or just a few.
2) A good tutorial for a simple TCP server / client can be found here
3) A TCP server is a process that waits for a connection from a TCP client. TCP stands for Transmission Control Protocol. From Wikipedia: TCP provides reliable, ordered delivery of a stream of bytes from a program on one computer to another program on another computer.
Lets say I have my C# app installed on 2 laptops connected to a WiFi Wireless Local Area Network.
How can these apps send messages to each other? What method or library can I use? I heard of using sockets but I have no idea how to work with these.
You could use WCF to build a communication pipe between the 2 applications. WCF encapsulates the sockets into a more manageable interface. You can start here.
Basically, you'll want to do it the same way you would in any other language. You'll open a network connection of one flavor or another (raw TCP or UDP, or a higher level protocol like HTTP) with one side acting as a server and the other acting as a client. Then each side can write data through or read data sent by the other side. It's can get pretty complicated from there. If you Google "C# Sockets" or "C# HTTP", etc, you'll find quite a few tutorials on the subject.
This is a very good article on sending C# objects (which could include whatever messages that you want to send) over a Socket connection using the Binary Formatter. Although it is not the most efficient, it is quite easy to grasp and get working.