我有一个处理和存储来自网页的传入订单的网络服务。
作为该Web服务的静态变量,根据this question,我有一台服务器,当接收到这样的订单时,它应该向连接的客户端发送一条非常小的消息。
以下是我服务器的代码。我只希望一次连接一个客户端,这可能解释了代码中的一些奇怪之处,但如果有人知道如何做得更好,我真的很想听听建议。
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()
}
}