开发者

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 th开发者_如何学运维is possible with ASP.NET/WCF?

Thanks


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!


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.


What you are trying to do would not work even if you really could do socket programming in Asp.Net. Asp.Net is not continuously "running" like a service is. It shuts down after a period of inactivity (no web requests made) and starts up again with new web requests. Your socket code would only run from when a web request made until that inactivity timeout occurs.


You don't need WCF or ASP.NET for that. You might look up UDP socket programming with .NET.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜