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