1

I have a web service that processes and stores incoming orders from a webpage.

As a static variable of that web service, according to this question I have a server that is supposed to send a very small message to the connected client when such an order is received.

Below is the code for my server. I only expect one client to connect at a time, which may explain some of the oddities in the code, but if someone knows how to do this better, I'd really like to hear suggestions.

TCP Server:

public class NotificationServer {
    private TcpListener tcpListener;
    private Thread listenThread;

    private NetworkStream clientStream;
    private TcpClient tcpClient;
    private ASCIIEncoding encoder;

    public NotificationServer() {
        tcpListener = new TcpListener();
        listenThread = new Thread(new ThreadStart(listenForClient));
        listenThread.Start();
        clientStream = null;
    }

    public bool sendOrderNotification() {
        byte[] buffer = encoder.GetBytes("o");

        clientStream.Write(buffer, 0, buffer.Length);

    }

    private void listenForClient() {
        tcpListener.Start();
        while (true) {
            // blocks until a client has connected to server
            tcpClient = tcpListener.AcceptTcpClient();
            clientStream = tcpClient.GetStream();
        }
    }
}

Web Service:

public class Service1 : System.Web.Services.WebService {
    public static NotificationServer notificationServer;

    public static Service1() {
        // start notification Server
        notificationServer = new NotificationServer();
    }

    [WebMethod]
    public void receiveOrder(string json) {
        // ... process incoming order

        // notify the order viewing client of the new order;
        notificationServer.sendOrderNotification()
    }
}
Community
  • 1
  • 1
lowerkey
  • 8,105
  • 17
  • 68
  • 102
  • Maybe you dont need this architecture at all. I can say take a look at nservicebus. it uses msmq and encourage async. http://nservicebus.com/docs/Samples/AsyncPages.aspx – adt Jan 31 '12 at 20:35
  • new link http://docs.particular.net/samples/web/asp-web-application/ – Peter Jan 29 '16 at 04:59

0 Answers0