Hello Everyone,
I have worked on sockets in winforms and console applications
but i am having some problem in writing the same for ASP.Net MVC application.
My Problem is
* How to use System.Net.Sockets in ASp.Net MVC Application to create a simple chat app.
Any ideas, samples or example will be very helpful to me.
I want the socket work interactively...
Thanking you.
What I have tried:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace sgsmSocket.Controllers
{
public class HomeController : Controller
{
string res = "";
Socket server, client;
byte[] _buffer;
public HomeController()
{
StartServer();
}
private void StartServer()
{
try
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Any, 25001));
server.Listen(0);
server.BeginAccept(new AsyncCallback(AcceptCallback), null);
res += ">> Listening";
//Response.Write("Server Running");
}
catch (Exception err)
{
res += ">> Listening Error " + err.Message;
}
}
private void AcceptCallback(IAsyncResult ar)
{
try
{
client = server.EndAccept(ar);
_buffer = new byte[ client.ReceiveBufferSize];
res += ">> Accepted";
client.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception err)
{
res += ">> Accept Error " + err.Message;
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
int received = client.EndReceive(ar);
Array.Resize(ref _buffer, received);
string text = Encoding.ASCII.GetString(_buffer);
Array.Resize(ref _buffer, client.ReceiveBufferSize);
res += ">> Received " + text;
client.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception err)
{
res += ">> Receiving Error " + err.Message;
}
}
//
// GET: /Home/
public ActionResult Index()
{
ViewBag.msg = res;
return View();
}
}
}