locked
How to interact between Windows Form & ASP.Net then send command to a TCP connection? RRS feed

  • Question

  • User-744646294 posted

    Hi, my current scenario:
    - A device, send data to Server via TCP only after a fixed time
    - A Windows Form application for async TCP listener (or acync Socket), receive data from devices and add to database
    - An web application (ASP.NET) to display data from database

    What I want to do now is: User click on a button on website and it will send a message to device.

    What I'm trying to do is store the message and after device send data successfully, I'll use that connection to send message and I need the way to send it from my website to Windows Form application. How can I achieve this?

    I'm also consider an alternate solution but it's too complex:
    - TCP connection will not be closed on both side
    - Store TCP connection in database so website can use it
    This solution may sound simple from first thought but when I try to do this, a lot of problems happened such as maintain connection in an object so I'll know connection belongs to which device. Update connection each second because there's a chance a connection can be lost either on server or device and new connection will be made with new information...

    While searching, I get some advise about ASP.NET signalR but from the document, it seems no option to receive TCP connection (Socket) from SignalR? Live user must be different with a device and login to system helped solve a lot of problem list above.

    Is there any way to improve my scenario solution? Please feel free to suggest. Thank you very much

    Tuesday, September 8, 2015 12:58 AM

Answers

  • User475983607 posted

    Let me try to explain this with an analogy.  TCP is like calling a friend on the telephone.  First you dial the number.  The phone rings and your friend picks up the receiver on the other end.  Since you and your friend speak the same langue you can easily communicate and relay information.  Eventually, the call is over and you hang up the phone.

    The language part of the call is similar to HTTP.

    If you want to talk to a web server you need to know the IP address and port (phone number) to establish a TCP connection.  For a web server this is whatever IP on port 80.  The server accepts the TCP connection (picks up the phone)  by responding with an SYN- ACK.  Now we have an open connection and we’re ready to talk.  The client sends an HTTP message to the server.

    POST from the client

    POST /default.aspx?foo=Hello HTTP/1.1
    Host: http://127.0.0.1:2738
    Content-Type: application/x-www-form-urlencoded
    User-Agent: SocketTest
    Content-Length:9
    bar=World

    The server's response

    HTTP/1.1 200 OK
    Server: ASP.NET Development Server/10.0.0.0
    Date: Wed, 09 Sep 2015 17:50:02 GMT
    X-AspNet-Version: 4.0.30319
    Transfer-Encoding: chunked
    Cache-Control: private
    Content-Type: text/xml; charset=utf-8
    Connection: Close
    
    <?xml version='1.0' encoding='utf-8' ?><root><foo>Hello</foo><bar>World</bar></root>
    

    And finally we hang up (FIN).

    What I’m trying to explain is you should consider using HTTP to communicate with the web server directly.  Then you can remove the Windows Forms TCP listener because you don’t need it.

    The same is true in reverse.  If the web server (or a browser) want to talk to the WiFi device, then the web server needs to know how to contact the WiFi device.  This on the other hand can be a little different depending on the network configuration.  Most likely you’ll need to NAT the WiFi device which is again out-of-scope for this forum.

    Here’s  is example code that shows how to use a socket to talk to a web server.

    Simple web form that is looking for a querystring and post data.

    string foo = Request["foo"];
    string bar = Request["bar"];
    Response.Clear();
    Response.ContentType = "text/xml";
    Response.Write(string.Format("<?xml version='1.0' encoding='utf-8' ?><root><foo>{0}</foo><bar>{1}</bar></root>", foo, bar));
                
    Response.Flush();
    Response.Clear();

    A console app that is uses TCP to open a socket with the web server and send an HTTP message.

            static void Main(string[] args)
            {
                SocketDemo();
            }
    
            private static void SocketDemo()
            { 
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];
    
            // Connect to a remote device.
            try {
                IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 2738);
    
                // Create a TCP/IP  socket.
                Socket sender = new Socket(AddressFamily.InterNetwork, 
                    SocketType.Stream, ProtocolType.Tcp );
    
                // Connect the socket to the remote endpoint. Catch any errors.
                try {
                    sender.Connect(remoteEP);
    
                    Console.WriteLine("Socket connected to {0}\r\n",
                        sender.RemoteEndPoint.ToString());
    
                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes(@"POST /default.aspx?foo=Hello HTTP/1.1
    Host: http://127.0.0.1:2738
    Content-Type: application/x-www-form-urlencoded
    User-Agent: SocketTest
    Content-Length:9
    
    bar=World");
    
                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);
                    Thread.Sleep(100);
    
                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
                    string result = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    Console.WriteLine(result);
    
                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    
                } catch (ArgumentNullException ane) {
                    Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
                } catch (SocketException se) {
                    Console.WriteLine("SocketException : {0}",se.ToString());
                } catch (Exception e) {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
    
            } catch (Exception e) {
                Console.WriteLine( e.ToString());
            }
            }

    You need to understand these basic concepts to move forward.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 9, 2015 2:01 PM
  • User1428246847 posted

    • I unfortunately don't have time to expand and really connect to a device (or server), so can't test that part. But it should be possible.

    Tested it now with a simple (echo) server that simulates your device; I'm aware that your device is a client but it's just to demonstrate the principle and it works.

    +----------------------+     +--------------------------------------+     +---------------------+
    | web page             |     | web service                          |     | server              |
    | button click         |     |                                      |     |                     |
    |   * call web method  |---->| connect to server and send a command |---->| process command     |
    |   * get reply        |<----| get reply and send to web page       |<----| send data to client |
    | display data         |     +--------------------------------------+     +---------------------+
    +----------------------+
    

    I don't now if a webservice can act as a server that your devices can connect to. I would probably add an additional layer (a windows service that takes the place of your windows forms application) between the web service and what is currently called 'server'.

    Notes:

    • Normal windows applications (windows forms, console, windows service) can also make use of your web service.
    • There is a dedicated section for wcf and asmx on this forum.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 10, 2015 5:50 AM

All replies

  • User1428246847 posted

    I think that what you're looking for is a web service that can be called from your website. No experience with it, but there are articles on the web about it do a search for asp.net website call a web service

    I don't see a need to have a Windows Form application as an intermediate step (if at all possible); the webservice should do the communication (website to device and back) as well as the database update.

    website <-> webservice <-> device
                     ^
                     |
                     +--> database

    I think that your Windows application can also make use of the webservice.

    Tuesday, September 8, 2015 3:04 AM
  • User-744646294 posted

    I would love to use WCF if possible but it seems impossible.
    - As I stated before, devices can only send data via TCP connection. Since they're not human, they don't need login, verify... they just send data after a fixed time to server. Human authentication (like chat application) actually make the scenario simpler but it's not for device.
    - If i'm not wrong WCF is HTTP based. Embedded TCP connection in HTTP connection, is it possible?
    - Actually, I tried search your suggestion before but most answer prefer use TCP or WCF only.

    Tuesday, September 8, 2015 4:06 AM
  • User1428246847 posted

    As I see it:

    • webpage sends command to webservice; e.g. "GetData 2" where 2 represents a device to access
    • webservice receives this and translates this to device specific command (e.g. "GiveMeTheData") and sends it to device 2
    • device replies with data (e.g. "HereItIs byte1 byte2 .... byteN")
    • webservice stores data in database and translates received data to return in a new command like "HereIsYourData 2 byte1 byte2 .... byteN"

    So there is no embedding of connections in connections.

    If the device returns values in pure text, you can leave the translation out (although there is probably a translation from/to XML or something between the webservice and the webpage

    Tuesday, September 8, 2015 5:32 AM
  • User-744646294 posted

    I'm still confusing. Devices can send/receive data by using TCP connection only. So:
    - Can we embedded TCP connection in WCF?
    - Can async TCP connection running WCF? (at the same time, it can connect to multiple devices).

    The use case will be: I use the website and want to see data of all devices at the same time. Code behind must somekind like: call web services -> create each TCP connection for each devices -> send/receive data and display at the same time in gridview

    Tuesday, September 8, 2015 6:13 AM
  • User1428246847 posted

    - Can we embedded TCP connection in WCF?

    I assume it can; as far as I know web services were designed for this type of work (communication between different computers). If it can't, you have to go the route of a normal (windows) service that at the one side acts as a tcp client (I assume it's a client) for communication with the device(s) and at the other side implements a very basic http server that can take commands from a browser / webpage (using get or post requests) and returns the requested data.

    Tuesday, September 8, 2015 6:48 AM
  • User475983607 posted

    Can we embedded TCP connection in WCF?

    That's the default behavior of WCF - HTTP and SOAP over TCP.

    Can async TCP connection running WCF? (at the same time, it can connect to multiple devices).

    WCF is a service that is usully run on IIS.  IIS can handle 1000s of concurrent connections.  For a service (web server) to open a socket on a remote device the server would need to know the device IP and Port.  This becomes more difficult when the device is behind a firewall or router.

    Embedded devices with TCP capability can simply open a socket and send an HTTP (Hypertext Transfer Protocol) message to a URL via HTTP GET or POST.  The target URL can be coded in such a way as to persist the data in a database.  Retrieving the data from a DB in ASP is very simple and well documented.

    I would not use WCF if the embedded device is TCP enabled.  WCF uses a SOAP formatted message to encapsulate data which in the embedded world would equate to yet another layer of code above the HTTP formatted message.

    The use case will be: I use the website and want to see data of all devices at the same time. Code behind must somekind like: call web services -> create each TCP connection for each devices -> send/receive data and display at the same time in gridview

    If you want real time monitoring of a process then consider using an embedded web server.  It makes the whole process a lot easier.  You can use a browser to interact with the device and HTTP is the main carrier of information on the Internet.  Otherwise, you'll need to come up with your own one-off protocol.

    I think the first thing you need to get a handle on is the HTTP protocol.  If you understand socket programming and TCP then HTTP is nothing more sending text down the wire. However, you 'll need a basic understanding of the protocol to get a web server or browser to behave they way you want.

    Tuesday, September 8, 2015 7:24 AM
  • User-744646294 posted

    mgebhard

    WCF is a service that is usully run on IIS.  IIS can handle 1000s of concurrent connections.  For a service (web server) to open a socket on a remote device the server would need to know the device IP and Port.  This becomes more difficult when the device is behind a firewall or router.

    Devices in my case is just hardware. It will be manual configure to connect to a specific IP & port of server, so I don't think we'll have trouble with firewall or router. The device can be turn off anytime or get new IP, so control its IP is impossible. We only know about it when it make a connection to our server (TCP listener). The server can not be TCP client.

    mgebhard

    If you want real time monitoring of a process then consider using an embedded web server.  It makes the whole process a lot easier.  You can use a browser to interact with the device and HTTP is the main carrier of information on the Internet.  Otherwise, you'll need to come up with your own one-off protocol

    Hardware can provide 2 options only: AT command (post/get) and TCP connection. AT command run so slow compare to TCP so I can't monitor it in real time. More over, let hardware know "someone want to send a message to you" seems impossible.

    So, the best way I think is:
    - user send some message and I'll store it
    - device connect to server via TCP, I know it and after receive I send the message to it also
    It can be done if I can send a message from ASP.NET to Windows Form application.

    Maybe embedded TCP in WCF is possible but hard to find some sample code. Do you have any suggestion about my case? Do you know ASP.NET signalR, can it help with my case?

    Tuesday, September 8, 2015 8:37 AM
  • User475983607 posted

    Devices in my case is just hardware. It will be manual configure to connect to a specific IP & port of server, so I don't think we'll have trouble with firewall or router. The device can be turn off anytime or get new IP, so control its IP is impossible. We only know about it when it make a connection to our server (TCP listener). The server can not be TCP client.

    Your original request sounds as though you wanted to make a remote connection to the embedded device. If the connects are always out bound from the embedded device then that's not a problem.

    Hardware can provide 2 options only: AT command (post/get) and TCP connection. AT command run so slow compare to TCP so I can't monitor it in real time. More over, let hardware know "someone want to send a message to you" seems impossible.

    Confused... I assume you mean the device control protocol uses AT commands over RS232 at some low baud rate as compared to a faster comm protocol like SPI? 

    So, the best way I think is:
    - user send some message and I'll store it
    - device connect to server via TCP, I know it and after receive I send the message to it also

    Confused... so you are sending a message to the device?  How?  Over TCP or a serial protocol from a host machine?

    It can be done if I can send a message from ASP.NET to Windows Form application.

    Again, confused... Is the Windows forms connected to the embedded device via the USB or serial port?

    Maybe embedded TCP in WCF is possible but hard to find some sample code. Do you have any suggestion about my case? Do you know ASP.NET signalR, can it help with my case?

    TCP is a communication protocol.  WCF by default uses TCP as the control protocol while messages are send via TCP using HTTP and SOAP.  SignalR uses web sockets essentially keeping a socket open and allowing messages to flow back an forth.  How many concurrent connections can the embedded device handle? 

    I have a lot of experience in this field but your questions don't make a whole lot of sense.  I kinda' understand what you're trying to do but I don't understand how everything is connected.

    Is the device connected to a host computer via a port like RS232 or USB?  Does the host use this port to configure the embedded device?  Once the device is configured is the host system using the port to retrieve data from the device via a Windows Forms application? 

    Tuesday, September 8, 2015 10:01 AM
  • User-744646294 posted

    mgebhard

    I have a lot of experience in this field but your questions don't make a whole lot of sense.  I kinda' understand what you're trying to do but I don't understand how everything is connected.

    Wow, thank you very much. You may be the one I'm looking for. I'll go more detail about my use case:

    - Hardware:
    + It can connect to wifi network
    + after connecting wifi, it'll make a TCP connection to server and send data after a specific time and keep repeating it

    - Server:
    + Windows Form for Ascyn TCP listener: receive data from any hardwares send to it at anytime then store it in database
    + Website ASP.NET for display the data from database (hosted in IIS)

    The above use case is already working and now the user want: they have ability to use website (web browser) and send some message to hardware

    So, my problem now is the TCP connection is in Windows Form, not from ASP.NET. I need to find the way to pass the message of user from web browser to server, server will send it to windows form then via TCP connection in windows form, I can send message back to hardware OR I must find better way to deal with this problem.

    What is your suggestion now?

    Tuesday, September 8, 2015 10:36 AM
  • User475983607 posted

    nhkduy90

    So, my problem now is the TCP connection is in Windows Form, not from ASP.NET. I need to find the way to pass the message of user from web browser to server, server will send it to windows form then via TCP connection in windows form, I can send message back to hardware OR I must find better way to deal with this problem.

    What is your suggestion now?

    If I understand, the WiFi hardware is communicating over TCP to a system running Windows Forms. I assume the message sent over TCP is some kind of custom protocol and the WiFi device knows how to find the Windows Forms application. Static IP? This Windows Forms application interprets the message sent from the WiFi device and relays this messages to the a central DB.  A separate ASP web application displays the data from the DB. Essentially, the Windows Forms application is acting as a proxy for the WiFi device.

    Now the users want to interact with the system in some way over the Internet but there is not direct connection to the WiFi device. You must go through the proxy (Windows Forms application) to communicate with the WiFi device. To complicate matters, the WiFi uses DHCP so the IP address will change over time.

    Just build a service on the Windows forms server that listens for a connection from the web server like you did for the WiFi device.  The WiFi device knows how to contact the Windows Forms application.  You should be able to grab the WiFi's IP address on each request and keep the IP cached for later use.  For example, when being contacted by the web server.

    IMHO, the architecture is a bit complex. If the WiFi device can handle DNS, I would remove the Windows Forms application and standardize on HTTP.  Generally, the technical hurtle with this type of setup is updating the WiFi device with a new image.  How you deal with updates is dependent on the hardware capabilities.  I generally use an SD card.

    Tuesday, September 8, 2015 11:49 AM
  • User-744646294 posted

    If I understand, the WiFi hardware is communicating over TCP to a system running Windows Forms. I assume the message sent over TCP is some kind of custom protocol and the WiFi device knows how to find the Windows Forms application. Static IP? This Windows Forms application interprets the message sent from the WiFi device and relays this messages to the a central DB.  A separate ASP web application displays the data from the DB. Essentially, the Windows Forms application is acting as a proxy for the WiFi device.

    I think it's a basic since server must always open and must have a static IP. The hardware will be set the IP and port from server.

    Just build a service on the Windows forms server that listens for a connection from the web server like you did for the WiFi device.  The WiFi device knows how to contact the Windows Forms application.  You should be able to grab the WiFi's IP address on each request and keep the IP cached for later use.  For example, when being contacted by the web server.

    So, you mean that web server now will have a TCP client function to connect with Windows Form? Is it possible to combine 2 TCP clients to a unique request?

    I would remove the Windows Forms application and standardize on HTTP

    You mean, use get/post? What happen if 2 or more users want to interact with hardware? Won't 1 TCP connection is better option?

    Tuesday, September 8, 2015 1:48 PM
  • User475983607 posted

    nhkduy90

    So, you mean that web server now will have a TCP client function to connect with Windows Form? Is it possible to combine 2 TCP clients to a unique request?

    I don't understand what you're asking.  TCP is a protocol that defines how data is communicated between two end points.  What makes a TCP connection unique is the sequence number or data within the packet like a timestamp, source IP, and data.

    If I understand the setup correctly, a Windows Forms application proxies data to the outside world.  It seems logical that this same proxy would work the other way as well and receive data from the outside world.  WiFi <-> Proxy (Windows Forms) <-> Web Server.

    I'm also assuming the proxy not only handles data it also transforms data to a format that the WiFi device understands.  I get the feeling you are not using HTTP. You are using a custom protocol.  The Windows Forms application performs this translation to communicate with the WiFi device.

    nhkduy90

    You mean, use get/post? What happen if 2 or more users want to interact with hardware? Won't 1 TCP connection is better option?

    GET/POST transactions occur over TCP.  Regardless, the bottle neck is most likely the WiFi device so you'll need to consult the device documentation.  Look for concurrent connections.  Most of the devices I've used have very beefy buffers and can handle several concurrent connections. There is also a dependency that the host microcontroller is programmed to take full advantage of the WiFi chipset. It is certainly possible that the WiFi chipset can handle 8 plus concurrent sockets but the micro is programmed to use one.

    Anyway, this discussion is way off topic for an ASP.NET general forum.  Consider contacting the WiFi manufacturer for suggestion on how to use the WiFi product.  Are you using one of the WizNet chipsets?

    Tuesday, September 8, 2015 2:37 PM
  • User-744646294 posted

    Well, we just send/receive bytes. It seems we still miscommunication. I'm stuck at sending message from webpage to hardware via WAN.

    Before, I asked about make webpage live to receive data transmit to server but everyone suggest that I must use Windows Form for socket (TCP) and webpage to display. Now I got more requirement and one of them is send message from webpage to devices.

    Let make an example:
    - I (at my place) use my device (ex: sdcard1 with ability to connect wifi) to connect to server (ex: in Azure)
    - The device automatically send some message every 5 minutes to server
    - You (at your place) use web browser and want to perform read image in sdcard1
    - At the same time, your friend (at their place) use web browser and want to perform erase the sdcard1
    - Someone use their device (ex: sdcard2) to connect to server too, the rest is the same with above
    - some more people with sdcard3, sdcard4 ... connect to server.
    *** All connection will be through WAN

    In this situation, what will you do to achieve the result?

    Tuesday, September 8, 2015 3:20 PM
  • User475983607 posted

    Well, we just send/receive bytes. It seems we still miscommunication. I'm stuck at sending message from webpage to hardware via WAN.

    Before, I asked about make webpage live to receive data transmit to server but everyone suggest that I must use Windows Form for socket (TCP) and webpage to display. Now I got more requirement and one of them is send message from webpage to devices.

    Let make an example:
    - I (at my place) use my device (ex: sdcard1 with ability to connect wifi) to connect to server (ex: in Azure)
    - The device automatically send some message every 5 minutes to server
    - You (at your place) use web browser and want to perform read image in sdcard1
    - At the same time, your friend (at their place) use web browser and want to perform erase the sdcard1
    - Someone use their device (ex: sdcard2) to connect to server too, the rest is the same with above
    - some more people with sdcard3, sdcard4 ... connect to server.
    *** All connection will be through WAN

    In this situation, what will you do to achieve the result?

    I wrote an application a few years back when Web API first came out that did something similar to what - I think - you're trying  to do.  It was a message application for embedded devices to communicate over the Internet or Intranet.  The principle was fairly easy.  Embedded controllers register themselves with a centralized service. The registration data was simply information on how to contact the each registered controller.  That allowed the controllers to talk to each other and share information.  The service could also be used by a web application to monitor all the registered controllers.

    Reading and writing to an SDCard and responding to HTTP requests is another story and way out-of-scope for a ASP.NET forum.   

    Tuesday, September 8, 2015 4:27 PM
  • User-744646294 posted

    mgebhard

    Reading and writing to an SDCard and responding to HTTP requests is another story and way out-of-scope for a ASP.NET forum.  

    No, read/write is just an example for you to understand what I'm trying to do. Currently:

    ASP.NET <> server (IIS + SQL server) <> windows form (host Asycn TCP listener) <> devices (reader with wifi & embedded TCP client + SD card)

    - The reader can read/write SDcard but it need a message from ASP.NET through wifi to know what to do
    - The reader embedded TCP client, so we can send message to it through TCP socket only
    - The reader TCP connection can be on or off anytime

    It would be great if it can reduce to something like this:
    Server <> ASP.NET <> ???? (have TCP listener) <> devices

    OR

    ASP.NET have ability to send some direct message to Windows Form. I'm thinking about putting message in database but I think if I keep checking it to match specific device, it can make server overload

    I hope this time you can understand clearly what I need

    Wednesday, September 9, 2015 1:56 AM
  • User475983607 posted

    Again, this has absolutely nothing to do with ASP.NET.

    I would shoot for this kind of configuration...

    [WiFi] <--> [REST Service] <--> [DB]
       |		   |
       -->[Browser]	   -->[Web App]

    The WiFi device will need at a minimum DHCP, DNS, and HTTP.  I always use use NTP and an RTC (real time clock) on my embedded designs but it is not required.  

    DNS is so the WiFi device can find the REST Service.

    HTTP is the protocol of the web.  If you don't use HTTP then you need to build a clunky one-off protocol which will make the project difficult to maintain and extend.  Also, HTTp allows browser to connect to the WiFi device directly.

    - The reader can read/write SDcard but it need a message from ASP.NET through wifi to know what to do

    Sure... This is all about the embedded program and the protocol used.

    - The reader embedded TCP client, so we can send message to it through TCP socket only

    Same as above however, I believe you mean TCP server not client!  TCP is like the telephone system.  The information passed over the phone line is the protocol.  HTTP is one of those protocols!

    - The reader TCP connection can be on or off anytime

    If the device is off then obviously it will not respond.  How this is handled is up to the design specifications.  Obviously, the Wifi device is assigned an IP vai DHCP.  So that's one way to find a device.  From there you can ping the device (ICMP).  In the past I've used NetBEUI.

    It would be great if it can reduce to something like this:
    Server <> ASP.NET <> ???? (have TCP listener) <> devices

    I don't understand what the server is the network diagram.  And it seems that your design requires extra systems, TCP listener, to aid the WiFi device.  I would not recommend this design.

    ASP.NET have ability to send some direct message to Windows Form. I'm thinking about putting message in database but I think if I keep checking it to match specific device, it can make server overload

    This kind of thing is generally handled with a networking protocol as stated above.

    I hope this time you can understand clearly what I need

    I understand what you're trying to do... the problem is you are looking for support in the wrong place.  You're on an ASP.NEt forum.  You need embedded development and networking support.

    Wednesday, September 9, 2015 7:31 AM
  • User-744646294 posted

    OK, just forget about my system. Can you give me more detail about HTTP system? I did it before I change completely to TCP Socket.

    Device send data somekind like: http://server/getdata.aspx?id=xxx&bac=xxxxxx&any=xxxxxx&.......
    It has a lot of query string, not somekind like simple chat, just a long message. Append too much query string in URL is not a good idea. While searching, I got limited on query string and device must cut it to send many times? Let say I can handle it.

    Now, to send message to it. Device must go to different page like: http://server/receivedata.aspx?long_query_string_with_a_lot_of_parameter. With limited on query string then it must go to receivedata1.aspx, receivedata2.aspx to get all message, won't it annoying? Send different message to unique device also had a lot of trouble.

    That's why I change to TCP Socket with bi-direction. The problem is the Socket connection is received by Windows Form, not ASP.NET then I need to pass it from ASP.NET to Windows Form. I can't integrate the live Socket into ASP.NET to listen any TCP connection at anytime

    I hope some detail about your system will give me some idea.

    Wednesday, September 9, 2015 9:58 AM
  • User475983607 posted

    nhkduy90

    That's why I change to TCP Socket with bi-direction. The problem is the Socket connection is received by Windows Form, not ASP.NET then I need to pass it from ASP.NET to Windows Form. I can't integrate the live Socket into ASP.NET to listen any TCP connection at anytime

    I hope some detail about your system will give me some idea.

    Your questions have nothing to do with ASP.NET.  I strongly suggest that you contact the WiFi manufacturer and/or microcontroller manufacturer and/or a network engineer for assistance. 

    Wednesday, September 9, 2015 12:03 PM
  • User-744646294 posted

    well, thank you for your help. I'll try to pass it through DB even though it will cause a little bit overload on server and try signalR later. Contact anyone is no use since I'm the one must create a working system to fulfill the requirement, not them with changing hardware, firmware.

    Wednesday, September 9, 2015 1:05 PM
  • User475983607 posted

    Let me try to explain this with an analogy.  TCP is like calling a friend on the telephone.  First you dial the number.  The phone rings and your friend picks up the receiver on the other end.  Since you and your friend speak the same langue you can easily communicate and relay information.  Eventually, the call is over and you hang up the phone.

    The language part of the call is similar to HTTP.

    If you want to talk to a web server you need to know the IP address and port (phone number) to establish a TCP connection.  For a web server this is whatever IP on port 80.  The server accepts the TCP connection (picks up the phone)  by responding with an SYN- ACK.  Now we have an open connection and we’re ready to talk.  The client sends an HTTP message to the server.

    POST from the client

    POST /default.aspx?foo=Hello HTTP/1.1
    Host: http://127.0.0.1:2738
    Content-Type: application/x-www-form-urlencoded
    User-Agent: SocketTest
    Content-Length:9
    bar=World

    The server's response

    HTTP/1.1 200 OK
    Server: ASP.NET Development Server/10.0.0.0
    Date: Wed, 09 Sep 2015 17:50:02 GMT
    X-AspNet-Version: 4.0.30319
    Transfer-Encoding: chunked
    Cache-Control: private
    Content-Type: text/xml; charset=utf-8
    Connection: Close
    
    <?xml version='1.0' encoding='utf-8' ?><root><foo>Hello</foo><bar>World</bar></root>
    

    And finally we hang up (FIN).

    What I’m trying to explain is you should consider using HTTP to communicate with the web server directly.  Then you can remove the Windows Forms TCP listener because you don’t need it.

    The same is true in reverse.  If the web server (or a browser) want to talk to the WiFi device, then the web server needs to know how to contact the WiFi device.  This on the other hand can be a little different depending on the network configuration.  Most likely you’ll need to NAT the WiFi device which is again out-of-scope for this forum.

    Here’s  is example code that shows how to use a socket to talk to a web server.

    Simple web form that is looking for a querystring and post data.

    string foo = Request["foo"];
    string bar = Request["bar"];
    Response.Clear();
    Response.ContentType = "text/xml";
    Response.Write(string.Format("<?xml version='1.0' encoding='utf-8' ?><root><foo>{0}</foo><bar>{1}</bar></root>", foo, bar));
                
    Response.Flush();
    Response.Clear();

    A console app that is uses TCP to open a socket with the web server and send an HTTP message.

            static void Main(string[] args)
            {
                SocketDemo();
            }
    
            private static void SocketDemo()
            { 
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];
    
            // Connect to a remote device.
            try {
                IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 2738);
    
                // Create a TCP/IP  socket.
                Socket sender = new Socket(AddressFamily.InterNetwork, 
                    SocketType.Stream, ProtocolType.Tcp );
    
                // Connect the socket to the remote endpoint. Catch any errors.
                try {
                    sender.Connect(remoteEP);
    
                    Console.WriteLine("Socket connected to {0}\r\n",
                        sender.RemoteEndPoint.ToString());
    
                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes(@"POST /default.aspx?foo=Hello HTTP/1.1
    Host: http://127.0.0.1:2738
    Content-Type: application/x-www-form-urlencoded
    User-Agent: SocketTest
    Content-Length:9
    
    bar=World");
    
                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);
                    Thread.Sleep(100);
    
                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
                    string result = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    Console.WriteLine(result);
    
                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                    
                } catch (ArgumentNullException ane) {
                    Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
                } catch (SocketException se) {
                    Console.WriteLine("SocketException : {0}",se.ToString());
                } catch (Exception e) {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
    
            } catch (Exception e) {
                Console.WriteLine( e.ToString());
            }
            }

    You need to understand these basic concepts to move forward.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 9, 2015 2:01 PM
  • User-744646294 posted

    If you want to talk to a web server you need to know the IP address and port (phone number) to establish a TCP connection.  For a web server this is whatever IP on port 80.  The server accepts the TCP connection (picks up the phone)  by responding with an SYN- ACK.  Now we have an open connection and we’re ready to talk.  The client sends an HTTP message to the server.

    Thank you very much but I already said above.  I used this method before. But the problem is the device's IP is not static, I can only track it when it connect to server and it can turn off or renew IP at anytime. There's no other way to know the present of device.

    One more problem I already said above also is when device use AT command to send HTTP request, it run very slow compare to TCP method (same hardware) and the hardware can not be changed. That's also a problem

    Thank you once again for your help. Even though it still can't help me but if you want, I can mark it as answer.

    Wednesday, September 9, 2015 2:52 PM
  • User1428246847 posted

    Thanks for letting me explore new stuff Cool

    I created a webservice to play as well as a console application and a webpage; the latter two make use of the webservice. I understand that webservices are a little outdated.

    Webservice

    Service1.asmx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    
    /*
     *  To create this project in VS2012, 
     *    select web in the left panel
     *    select .net framework 3.5
     */
    namespace WebService1
    {
        /// <summary>
        /// Summary description for Service1
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        // [System.Web.Script.Services.ScriptService]
        public class Service1 : System.Web.Services.WebService
        {
    
            [WebMethod]
            public string HelloWorld()
            {
                return "Hello World";
            }
    
            [WebMethod]
            public string[] getDirListing(string strPath)
            {
                return System.IO.Directory.GetFiles(strPath);
            }
    
            [WebMethod]
            public byte[] getDeviceData(int iDevicenum)
            {
                byte[] receiveddata = null;
    
                // connect to device
    
                // send command
    
                // get reply and store in receiveddata
    
                // cleanup connection
    
                /*
                 * simulate some data
                 */
                receiveddata = new byte[256];
                Random rnd = new Random();
                rnd.NextBytes(receiveddata);


    // return the data return receiveddata; } } }

    The webservice has two three methods; the first one is a standard one if I'm not mistaken, the second one retrieves a directory listing of a specified directory on the server and the third one shows how I see that you can get device data.

    Next I created a web application and webpage in the same project (this should not be necessary; do some research) and added a reference to the webservice.

    Markup

    <asp:Label ID="Label1" runat="server" Text="Directory"></asp:Label>
    <asp:TextBox ID="tbDrive" runat="server"></asp:TextBox>
    <asp:Button ID="btnRequest" runat="server" Text="Request" OnClick="btnRequest_Click"/>
    <br />
    <asp:ListBox ID="lbResult" runat="server"></asp:ListBox>
    <br />
    <asp:Label ID="lblData" runat="server" Text="Click request to get data from device"></asp:Label>

    Code behind

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    lbResult.Visible = false;
                    tbDrive.Text = "C:\\";
                }
                else
                {
                }
            }
    
            protected void btnRequest_Click(object sender, EventArgs e)
            {
                WebService1.Service1 ws = new WebService1.Service1();
                List<string> lstFiles = ws.getDirListing(tbDrive.Text).ToList<string>();
                if (lstFiles != null && lstFiles.Count != 0)
                {
                    lbResult.DataSource = lstFiles;
                    lbResult.DataBind();
                    lbResult.Visible = true;
                }
                else
                {
                    lbResult.Visible = false;
                }
    
                byte[] receiveddata = ws.getDeviceData(1);
                if (receiveddata == null)
                    lblData.Text = "Error";
                else if (receiveddata.Length == 0)
                    lblData.Text = "No data";
                else
                    lblData.Text = BitConverter.ToString(receiveddata);

    } } }

    This basically shows how you can use the methods in the webservice. The first part of the btnRequest_Click method retrieves a directory listing and displays it in a listbox, the second part shows the result of geting the data from a device.

    Notes:

    • I unfortunately don't have time to expand and really connect to a device (or server), so can't test that part. But it should be possible.
    • If you go this way, read up on webservices
    • //EDIT: Only tested from within VS; no publishing in IIS

    References used:

    1. http://www.codeproject.com/Articles/863/Your-first-C-Web-Service
    2. http://www.c-sharpcorner.com/UploadFile/4d9083/create-simple-web-service-in-visual-studio-2008-2010-2012/

    Thursday, September 10, 2015 1:26 AM
  • User1428246847 posted

    • I unfortunately don't have time to expand and really connect to a device (or server), so can't test that part. But it should be possible.

    Tested it now with a simple (echo) server that simulates your device; I'm aware that your device is a client but it's just to demonstrate the principle and it works.

    +----------------------+     +--------------------------------------+     +---------------------+
    | web page             |     | web service                          |     | server              |
    | button click         |     |                                      |     |                     |
    |   * call web method  |---->| connect to server and send a command |---->| process command     |
    |   * get reply        |<----| get reply and send to web page       |<----| send data to client |
    | display data         |     +--------------------------------------+     +---------------------+
    +----------------------+
    

    I don't now if a webservice can act as a server that your devices can connect to. I would probably add an additional layer (a windows service that takes the place of your windows forms application) between the web service and what is currently called 'server'.

    Notes:

    • Normal windows applications (windows forms, console, windows service) can also make use of your web service.
    • There is a dedicated section for wcf and asmx on this forum.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 10, 2015 5:50 AM
  • User-744646294 posted

    I don't now if a webservice can act as a server that your devices can connect to. I would probably add an additional layer (a windows service that takes the place of your windows forms application) between the web service and what is currently called 'server'.

    Actually my application at first is just a windows service. However, it need to connect to database so I changed it to Windows Form so user can interact with it. Thank you for your contribution but it still no use with my case. Currently, saving and calling DB too much in a very small time at this time cause server always overload. I'll try find new way to improve it

    Friday, September 11, 2015 10:08 PM
  • User1428246847 posted

    Actually my application at first is just a windows service. However, it need to connect to database so I changed it to Windows Form so user can interact with it.

    You should have kept it as a service ;) Modify it so it can also communicate with the desktop application by implementing a TCP server that the windows form application can connect to and use to send commands to devices and get data from them. That same server side of the service can be used by a webservice.

    Currently, saving and calling DB too much in a very small time at this time cause server always overload.

    Except for optimizing the database tables there is not much that you can do about it. Better hardware will help (to a degree).

    I think that your opening post has sufficiently been answered. Please consider to mark one or more replies as 'answer' so this thread can be seen as 'finished'.

    Saturday, September 12, 2015 1:45 AM
  • User-744646294 posted

    You should have kept it as a service ;) Modify it so it can also communicate with the desktop application by implementing a TCP server that the windows form application can connect to and use to send commands to devices and get data from them. That same server side of the service can be used by a webservice.

    Well:
    - Currently I'm doing: Windows Form <> Database <> ASP.NET
    - Your suggest: Windows Form <> (Web service <> Database) <> ASP.NET

    Except for optimizing the database tables there is not much that you can do about it. Better hardware will help (to a degree).

    I think that your opening post has sufficiently been answered. Please consider to mark one or more replies as 'answer' so this thread can be seen as 'finished'.

    Maybe add some static List to store message in Web Service will reduce the call to database and help server a little bit.

    Actually, I'm still not satisfy, but I will mark your last code as answered. I'll try play around with web service to check performance and try signalR or WebSocket later.

    Saturday, September 12, 2015 2:45 AM