Как создать tcp-сервер, который отправляет уведомления клиенту при получении заказа веб-сервисом? - PullRequest
1 голос
/ 01 февраля 2012

У меня есть веб-сервис, который обрабатывает и сохраняет входящие заказы с веб-страницы.

Как статическая переменная этого веб-сервиса, согласно этот вопрос У меня есть сервер, который долженотправить очень маленькое сообщение подключенному клиенту при получении такого заказа.

Ниже приведен код моего сервера.Я ожидаю, что одновременно подключается только один клиент, что может объяснить некоторые странности в коде, но если кто-то знает, как это сделать лучше, мне бы очень хотелось услышать предложения.

TCP-сервер:

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();
        }
    }
}

Веб-служба:

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()
    }
}
...