I'm writing a TCP Server as a UWP app in C# and want to poll a list of clients to check for messages. The client list is a list of StreamSockets.
In regular C#, I can just check the NetworkStream to see if data is available. Is there a way of dong this in UWP? I am currently using:
mClient.InputStream.ReadAsync(streamBuffer, MessageHeader.HEADER_LENGTH, InputStreamOptions.None).AsTask().Wait(//Some amount of ms);
This is poor, as for many clients then the delay is going to become too high. There also seems to be a race condition, that unless the total read amount has been met, the task still fails to complete.
I'm looking for something semantically identical to this:
if (mNetworkStream.DataAvailable)
{
mClient.Client.Receive(mBuffer, 1, SocketFlags.Peek);
Is this possible?
Ok, so a bit more context to this. I am using Unity, and didn't realise that since the introduction of the IL2CPP scripting backend, that the System.Net.Sockets can be used in UWP. This means that I don't have to use any of the restrictive UWP socket wrappers.
Thanks #jdweng, I started to implement the multiple listener variation until I found out that I can use my existing .Net implementation!
Related
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.
I am working on a project where i need to connect with multiple clients and every client is streaming live screen capturing to server. Server show that.
What would be the best approach for that.
Thank You
You can use WCF in streaming mode for the video, but I doubt it is a good solution.
I think that going for pure sockets is better, to get the performance required. Showing a live video stream is also not really a limited operation (which is what WCF is built for), but rather something ongoing.
My suggestiion is to:
Use a pure TCP socket for the video stream for a start.
If that gives problems, you can switch to UDP. It is better to skip over any lost packages for live video, but with UDP you have to track package ordering etc. yourself.
If you need control operations, use a separate WCF service for that.
I'm thinking like the methods games like Counter Sstrike, WoW etc uses. In CS you often have just like 50 ping, is there any way to send information to an online MySQL database at that speed?
Currently I'm using an online PHP script which my program requests, but this is really slow, because the program first has to send headers and post-information to it, and then retrieve the result as an ordinary webpage.
There really have to be any easier, faster way of doing this? I've heard about TCP/IP, is this what I should use here? Is it possible for it to connect to the database in a faster way than indirectly via the PHP script?
TCP/IP is made up of three protocols:
TCP
UDP
ICMP
ICMP is what you are using when you ping another computer on a network.
Games, like CounterStrike, don't care about what you previously did. So there's no requirement for completeness, to be able to reconstruct what you did (which is why competitors have to tape what they are doing). This is what UDP is used for - there's no guarantee that data is delivered or received. Which is why lag can be such a problem - you're already dead, you just didn't know it.
TCP guarantees that data is sent and received. Slower than UDP.
There are numerous things to be aware of to have a fast connection - less hops, etc.
Client-to-server for latency-critical stuff? Use non-blocking UDP.
For reliable stuff that can be a little slower, if you use TCP make sure you do so in a non-blocking fashion (select(), non-blocking send, etc.).
The big reason to use UDP is if you have time-sensitive data - if the position of a critter gets dropped, you're better off ignoring it and sending the next position packet rather than re-sending the last one.
And I don't think any high-performance game has each and every call resolve to a call to the database. It's more common to (if a database is even used) persist data occasionally, or at important events.
You're not going to implement Counterstrike or anything similar on top of http.
Most games like the ones you cite use UDP for this (one of the TCP/IP suite of protocols.) UDP is chosen over TCP for this application since it's lighter weight allowing for better performance and TCP's reliability features aren't necessary.
Keep in mind though, those games have standalone clients and servers usually written in C or C++. If your application is browser-based and you're trying to do this over HTTP then use a long-lived connection and strip back the headers as much as possible, including cookies. The Tornado framework may be of interest to you there. You may also want to look into HTML5 WebSockets however widespread support is still a fair way off.
If you are targeting a browser-based plugin like Flash, Java, SilverLight then you may be able to use UDP but I don't know enough about those platforms to confirm.
Edit:
Also worth mentioning: once your networking code and protocol is sufficiently optimized there are still things you can do to improve the experience for players with high pings.
Is there something like twisted (python) or eventmachine (ruby) in .net land?
Do I even need this abstraction? I am listening to a single IO device that will be sending me events for three or four analog sensors attached to it. What are the risks of simply using a looped UdpClient? I can't miss any events, but will the ip stack handle the queuing of messages for me? Does all of this depend on how much work the thread tries to do once I receive a message?
What I'm looking for in an abstraction is to remove the complication of threading and synchronization from the problem.
I think you are making it too complicated.
Just have 1 UDP socket open, and set an async callback on it. For every incoming packet put it in a queue, and set the callback again. Thats it.
make sure that when queuing and dequeueing you set a lock on the queue.
it's as simple as that and performance will be great.
R
I would recommend ICE it's a communication engine that will abstract threading and communication to you (documentation is kind of exhaustive).
Problem is that with Udp you are automatically assuming the risk of lost packets. I've read the documentation on ICE (as Steve suggested), and it is very exhaustive. It appears that ICE will work for Udp, however, it appears that Tcp is preferred by the developers. I gather from the ICE documentation that it does not provide any intensive mechanisms to ensure reliable Udp communications.
It is actually very easy to set up an asynchronous Udp client or server. Your real work comes in checking for complete packets and buffering. The asynchronous implementations should keep you from managing threads.
It sounds like you are looking for reliable multicast -You could try RMF , it will do the reliability and deliver the messages using asyc callbacks from the incoming message queue. IBM also does WebSphere which has a UDP component. EmCaster is also an option - however development seems to have stopped back in 2008.
If you aren't going to be transmitting these packets (or events) to other machines you might just want to use something simple like memory mapped files or other forms of IPC.
I'm an embedded programmer trying to do a little bit of coding for a communications app and need a quick start guide on the best / easiest way to do something.
I'm successfully sending serial data packets but need to impliment some form of send/ response protocol to avoid overflow on the target system and to ensure that the packet was received ok.
Right now - I have all the transmit code under a button click and it sends the whole lot without any control.
What's the best way to structure this code , i.e sending some packets - waiting for response .. sending more .. etc etc until it's all done, then carrying on with the main program.
I've not used threads or callbacks or suchlike in this environment before but will learn - I just need a pointer to the most straigtforward ways to do it.
Thanks
Rob
The .NET serialport uses buffers, learn to work with them.
Sending packets that are (far) smaller than the Send-buffer can be done w/o threading.
Receiving can be done by the DataReceived event but beware that that is called from another thread. You might as well start your own thread and use blocking reads from there.
The best approach depends on what your 'packets' and protocol look like.
I think to have a long experience about serial comm, both MCU and PC-based.
I strongly UNSUGGEST the single-thread based solution, although it is very straigthful for light-speed testing, but absolutely out for final releases.
Surely you may choose among several patterns, but they are mostly shaped around a dedicated thread for the comm process and a finite-state-machine to parse the protocol (during receiveing).
The prevoius answers give you an idea to how build a simple program, but it might depends on the protocol specification, target device, scope of the application, etc.
there are of course different ways.
I will describe a thread based and an async operation based way:
If you don't use threads, your app will block as long as the operation is performing. This is not what a user is expecting today. Since you are talking about a series of sending and receiveing commands, I would recommend starting the protocol as a thread and then waiting for it to finish. You might also place an Abort button if neccesary. Set the ReadTimeout values and at every receive be ready to catch the exception! An introducing into creating such a work thread is here
If you want to, use Async Send/Receive functions instead of a thread (e.g. NetworkStream.BeginRead etc.). But this is more difficult because you have to manage state between the calls: I recommend using a Finite State Machine then. In fact you create an enumeration (i.e. ProtocolState) and change the state whenever an operation has completed. You can then simply create a function that performs the next step of the protocol with a simple switch/case statement. Since you are working with a remote entity (in your case the serial target system), you always have to consider the device is not working or stops working during the protocol. Do this by starting a timeout timer (e.g. set to 2000ms) and start it after sending each command (assuming each command will get a reply in your protocol). Stop it if the command was received successfully or on timeout.
You could also implement low-level handshaking on the serial port; set the serial port's Handshake property to rts/cts or xon/xoff.
Otherwise (or in addition), use a background worker thread. For simple threads, I like a Monitor.Wait/Pulse mechanism for managing the thread.
I have some code that does read-only serial communications in a thread; email me and I'll be happy to send it to you.
I wasn't sure from your question if you were designing both the PC and embedded sides of the communication link, if you are you might find this SO question interesting.