Web ページからの注文を処理して保存する Web サービスがあります。
そのWebサービスの静的変数として、この質問によれば、そのような注文が受信されたときに、接続されたクライアントに非常に小さなメッセージを送信することになっているサーバーがあります。
以下は私のサーバーのコードです。一度に接続できるクライアントは 1 つだけだと思いますが、これがコードのいくつかの奇妙な点を説明している可能性がありますが、誰かがこれをより適切に行う方法を知っている場合は、提案を聞きたいと思っています。
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()
}
}