1

我有一个 Web 服务,可以处理和存储来自网页的传入订单。

作为该 Web 服务的静态变量,根据这个问题,我有一个服务器,它应该在收到这样的订单时向连接的客户端发送一条非常小的消息。

下面是我的服务器的代码。我只希望一次连接一个客户端,这可能解释了代码中的一些奇怪之处,但如果有人知道如何更好地做到这一点,我真的很想听听建议。

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

0 回答 0