Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket Programming in ASP.NET?

Can we do Socket Programming in ASP.NET/WCF? Like the service listens on a port for incoming requests. All the clients from outside the network also publish/listen on that ip:port

Whenever the service writes anything on the port, all the clients get that thing without polling.

Is something like this possible with ASP.NET/WCF?

Thanks

like image 438
Jayesh Avatar asked Jul 07 '11 17:07

Jayesh


2 Answers

As alexanderb linked, there is indeed .NET socket support in the System.Net.Sockets namespace. As I just completed, with a colleague, a WCF web service that communicates with a socket-based service in Korea. We're simply sending some info and getting some info back, quick, tidy. Here's an example of some sockety code:

const string ipAddressString = "xxx.xxx.xxx.xxx";// replace with correct IP address
IPAddress ipAddress = IPAddress.Parse(ipAddressString);
const int portNum = 1234;// replace with correct port
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, portNum);

Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(remoteEndPoint);
string sendString = "some stuff you want to send";
byte[] bytes = Encoding.UTF8.GetBytes(sendString.ToString());
client.Send(bytes);
byte[] receiveBuffer = new byte[128];
client.Receive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None);
string bufferString = Encoding.GetEncoding(949).GetString(receiveBufferSize);
client.Shutdown(SocketShutdown.Both);
client.Close();

try-catches and such have been omitted to keep this as "simple" and socket-focused as possible. The key takeaways here are the Socket construction, Connect(), Send(), and Receive(). Also, Shutdown() and Close(). Note that before about three days ago, I thought a socket was that thing on the wall you plug stuff into, so this should be fairly rudimentary. But hey, it works!

like image 58
MrBoJangles Avatar answered Sep 21 '22 08:09

MrBoJangles


If you are talking about WCF/ASP.NET, those two are much "higher" above the socket level. Answering you question - yes, you can do socket programming with .NET framework.

http://msdn.microsoft.com/en-us/library/system.net.sockets.aspx

EDIT

BTW, I smell something wrong then hear "sockets.. cloud", you are probably missing something. Taking into account avaliable techlologices for distributed/networking programming doing socket programming nowadays seems illogical.

like image 44
Alexander Beletsky Avatar answered Sep 24 '22 08:09

Alexander Beletsky