Chapter98:Networking

No Comments

Section98.1:BasicTCPCommunicationClient

ThiscodeexamplecreatesaTCPclient,sends”HelloWorld”overthesocketconnection,andthenwritestheserver response to the console before closing the connection.

//DeclareVariables

stringhost=”stackoverflow.com”;

intport=9999;

inttimeout=5000;

//CreateTCPclientandconnect

using(var_client=newTcpClient(host,port))

using(var_netStream=_client.GetStream())

{

_netStream.ReadTimeout=timeout;

//Writeamessageoverthesocket

stringmessage=”HelloWorld!”;

byte[]dataToSend=System.Text.Encoding.ASCII.GetBytes(message);

_netStream.Write(dataToSend,0,dataToSend.Length);

//Readserverresponse

byte[]recvData=newbyte[256];

intbytes=_netStream.Read(recvData,0,recvData.Length);

message=System.Text.Encoding.ASCII.GetString(recvData,0,bytes); Console.WriteLine(string.Format(“Server: {0}”,message));

};//Theclientandstreamwillcloseascontrolexitstheusingblock(Equivilentbutsaferthan callingClose();

Section98.2: Download a file froma web server

Downloading a file from the internet is a very common task required by almost every application your likely to build.

Toaccomplishthis,youcanusethe”System.Net.WebClient”class.

Thesimplestuseofthis,usingthe”using”pattern,isshownbelow:

using(varwebClient=newWebClient())

{

webClient.DownloadFile(“http://www.server.com/file.txt”,”C:\\file.txt”);

}

What this example does is it uses “using” to make sure that your web client is cleaned up correctly when finished, and simply transfers the named resource from the URL in the first parameter, to the named file on your local hard drive in the second parameter.

Thefirstparameterisoftype”System.Uri”,thesecondparameterisoftype”System.String”

You can also use this function is an async form, so that it goes off and performs the download in the background, while your application get’s on with something else, using the call in this way is of major importance in modern applications, as it helps to keep your user interface responsive.

WhenyouusetheAsyncmethods,youcanhookupeventhandlersthatallowyoutomonitortheprogress,sothat

youcould forexample, updatea progress bar,something likethe following:

varwebClient=newWebClient())

webClient.DownloadFileCompleted+=newAsyncCompletedEventHandler(Completed); webClient.DownloadProgressChanged+=newDownloadProgressChangedEventHandler(ProgressChanged); webClient.DownloadFileAsync(“http://www.server.com/file.txt”,”C:\\file.txt”);

OneimportantpointtorememberifyouusetheAsyncversionshowever,andthat’s”Beverycarefullaboutusing them in a ‘using’ syntax”.

The reason for this is quite simple. Once you call the download file method, it will return immediately. If you have this in a using block, you will return then exit that block, and immediately dispose the class object, and thus cancel your download in progress.

If you use the ‘using’ way of performing an Async transfer, then be sure to stay inside the enclosing block until the transfer completes.

Section98.3:AsyncTCPClient

Using async/awaitin C# applications simplifies multi-threading. This is how you can use async/awaitin conjunction with a TcpClient.

//DeclareVariables

stringhost=”stackoverflow.com”;

intport=9999;

inttimeout=5000;

//CreateTCPclientandconnect

//Thengetthenetstreamandpassit

//ToourStreamWriterandStreamReader

using(varclient=newTcpClient())

using(varnetstream=client.GetStream())

using(varwriter=newStreamWriter(netstream))

using(varreader=newStreamReader(netstream))

{

//Asynchronslyattempttoconnecttoserver

awaitclient.ConnectAsync(host,port);

//AutoFlushtheStreamWriter

//sowedon’tgooverthebuffer

writer.AutoFlush=true;

//Optionallysetatimeout

netstream.ReadTimeout=timeout;

//WriteamessageovertheTCPConnection

stringmessage=”HelloWorld!”;awaitwriter.

WriteLineAsync(message);

//Readserverresponse

stringresponse=awaitreader.ReadLineAsync();

Console.WriteLine(string.Format($”Server:{response}”));

}

//Theclientandstreamwillcloseascontrolexits

//theusingblock(EquivilentbutsaferthancallingClose();

Section98.4:BasicUDPClient

This code example creates a UDP client then sends “Hello World” across the network to the intended recipient. A listenerdoesnothavetobeactive,asUDPIsconnectionlessandwillbroadcastthemessageregardless.Oncethe message is sent, the clients work is done.

byte[]data=Encoding.ASCII.GetBytes(“HelloWorld”);

stringipAddress=”192.168.1.141″;

stringsendPort=55600; try

{

using(varclient=newUdpClient())

{

IPEndPointep=newIPEndPoint(IPAddress.Parse(ipAddress),sendPort); client.Connect(ep);

client.Send(data,data.Length);

}

}

catch(Exceptionex)

{

Console.WriteLine(ex.ToString());

}

BelowisanexampleofaUDPlistenertocomplementtheaboveclient.Itwillconstantlysitandlistenfortrafficona givenportandsimplywritethatdatatotheconsole.Thisexamplecontainsacontrolflag’done’thatisnotset internallyandreliesonsomethingtosetthistoallowforendingthelistenerandexiting.

booldone=false;

intlistenPort=55600;

using(UdpClinetlistener=newUdpClient(listenPort))

{

IPEndPointlistenEndPoint=newIPEndPoint(IPAddress.Any,listenPort); while(!done)

{

byte[]receivedData=listener.Receive(reflistenPort);

Console.WriteLine(“Receivedbroadcastmessagefromclient{0}”,listenEndPoint.ToString());

Console.WriteLine(“Decodeddatais:”);

Console.WriteLine(Encoding.ASCII.GetString(receivedData));//shouldbe”HelloWorld”sentfromaboveclient

}

}

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Recent Posts

Leave a Comment