1

I was given a task of writing a server socket, which would respond to different url paths. Each url path should call a specific method on the server. For example:

http://localhost/init
http://localhost/method1
http://localhost/method2

I don't know if this is possible with sockets and I also think this should be possible with web (REST) services. Is this also possible with sockets?

Looking at server side socket examples [1], they all have a fixed url.

TheAptKid
  • 1,559
  • 3
  • 25
  • 47
  • Could you go into little more detail about what problem you are trying to solve? – HansP Dec 10 '15 at 08:21
  • _"Looking at server side socket examples [1], they all have a fixed url."_ - TCP sockets don't connect to urls but rather IP addresses. HTTP is a layer above TCP and hides all the gobble-de-gook of TCP –  Dec 10 '15 at 08:35

2 Answers2

2

I am not a C# expert, but I already programmed some small webservers with Java-Sockets. Essentially a http-requests use a TCP Socket. So technical a REST-Service is implemented by using these sockets.

http://localhost/init will send a http request with an http-get header to localhost. The header will look kind off like this:

GET /init HTTP/1.1
Host: localhost

You can see, that you can read the first line and decide what URL you requested ("init" in this case). You should definitly read something about http-protocoll and http-header before you start writing a small webserver on sockets.

red13
  • 427
  • 4
  • 12
  • I think this is what I'm looking for. Now I just have to figure out how to get the request headers and parse them. – TheAptKid Dec 10 '15 at 12:36
  • If you have a TCP-Connection you can read the header from its stream directly afterwards. Just think about a method for splitting the header. I used regular expressions, but you can use what you want. – red13 Dec 10 '15 at 12:41
1

That tutorial you link to is horrible, don't use it to learn sockets from. Sockets are programming language agnostic, so buy a good book on network programming if you actually want to learn something.

Then you'll learn networking is visualized and abstracted through the use of layers. Sockets abstract all the messy network layers for you, giving you a byte stream to read from and write into.

This alone does not let two applications talk. You need an application protocol layered over this socket in order to frame your messages. HTTP is one such protocol.

So there is no such thing as "sockets instead of HTTP". You can't have HTTP without sockets (technically you can, but nobody does it). REST, in turn, is layered on top of HTTP.

So you just want to use ASP.NET Web API. This offers you an easy to program REST interface, hiding all the details of HTTP, sockets and everything beneath.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272