Is the NS-3 TCP/UDP socket non-blocking or blocking? - sockets

I am trying to implement a multimedia server application in NS-3 which can serve multiple clients.
Can a single NS-3 (TCP? and/or) UDP socket accept multiple simultaneous connections?

As stated in the ns-3 socket documentation, all socket calls in ns-3 are non-blocking (in contrast to the original socket API). This is a direct result of the asynchronous and event-based implementation model of ns-3.
The core concept to model a blocking socket call is to register a call-back which is invoked once a connection is established or data becomes available. One of these calls is ns3::Socket::SetRecvCallback which you can use to react to incoming packets
Of course, ns-3 can be used to implement a server that accepts multiple connections. For this purpose, you need to register to a call-back function such as ns3::Socket::SetRecvCallback and then to dispatch the received data adequately.

Related

Does data loss happens in fast sender and very slow receiver?

I have an application consisting of client and server by making use of sockets.
On the server side in the thread where it is receiving messages from client i have made a sleep call for 10 sec.Now when i send messages from client 1000000 times to server then messages being received from server is very slowly.My question is as follows:
-Does it mean that the receiving call on server side is blocking call?
-Secondly,is there any good document which can make me understand better the blocking and non blocking behavior of send and receive call of sockets.
Depends on whether you're using TCP or UDP sockets. TCP guarantees delivery, UDP doesn't. So in a UDP application packets can be dropped for any number of reasons, including if the servers sends too quickly to the client.
By default, calls on sockets are blocking calls. You have to set non-blocking explicitly.

Separate threads for socket send/recv?

I'm weighing up how to implement a TCP based server (in C) - the server will accept a connection from a client, receive commands from the client, and then send the response. Pretty simple stuff - but the processing of the command must be done by another thread in the system, which introduces a bit of concurrency to the mix.
So I'm trying to decide whether to handle all TCP comms in one thread, using non-blocking sockets and select(), or to use blocking sockets and two separate comms threads (one for sending, one for receiving).
My concern about the latter is handling socket synchronisation - if I close the socket in the send thread, what happens in the receive thread (or vice versa) .. and how to deal with this and clean up in the correct manner.
Any advice would be much appreciated.
You do not need separate receive and send threads for a client. When the client is accepted, create one thread that handles all of the I/O for that client, both receiving and sending (especially since you are implementing a command/response protocol). But if you do choose to use separate threads, closing a socket in one thread will cause detectable errors in the other thread that is using the same socket. Simply terminate each thread when a socket error occurs, and then decide which thread is going to be responsible for closing the socket.
However, if you need to handle a high number of concurrent clients then threading is not the best choice. Asynchronous I/O using non-blocking sockets (or on Windows, using I/O Completion Ports) is better, as it requires a smaller number of threads.

Differences between TCP sockets and web sockets, one more time [duplicate]

This question already has answers here:
What is the fundamental difference between WebSockets and pure TCP?
(4 answers)
Closed 4 years ago.
Trying to understand as best as I can the differences between TCP socket and websocket, I've already found a lot of useful information within these questions:
fundamental difference between websockets and pure TCP
How to establish a TCP Socket connection from a web browser (client side)?
and so on...
In my investigations, I went through this sentence on wikipedia:
Websocket differs from TCP in that it enables a stream of messages instead of a stream of bytes
I'm not totally sure about what it means exactly. What are your interpretations?
When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer. If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.
But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned corresponds to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the recipient of a message is event-driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.
Note that you can do message based communication using TCP sockets, but you need some extra layer/encapsulation that is adding framing/message boundary data to the messages so that the original messages can be re-assembled from the pieces. In fact, WebSockets is built on normal TCP sockets and uses frame headers that contains the size of each frame and indicate which frames are part of a message. The WebSocket API re-assembles the TCP chunks of data into frames which are assembled into messages before invoking the message event handler once per message.
WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.
The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).
Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.
To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

iPhone Native system routines(datagram-socket-type)

Sockets are full-duplex communication
channels between processes either
local to the same host machine or
where one process is on a remote host.
Unlike pipes, in which data goes in
one direction only, sockets allow
processes both to send and receive
data. NSFileHandle facilitates
communication over stream-type sockets
by providing mechanisms run in
background threads that accept socket
connections and read from sockets.
NSFileHandle currently handles only
communication through stream-type
sockets. If you want to use datagrams
or other types of sockets, you must
create and manage the connection using
native system routines.
The process on one end of the
communication channel (the server)
starts by creating and preparing a
socket using system routines. These
routines vary slightly between BSD and
non-BSD systems, but consist of the
same sequence of steps:
Create a stream-type socket of a
certain protocol.
Bind a name to the socket.
Adding itself as an observer of
NSFileHandleConnectionAcceptedNotification.
Sending acceptConnectionInBackgroundAndNotify
to this file handle object.
This method accepts the connection in the
background, creates a new NSFileHandle
object from the new socket descriptor,
and posts an NSFileHandleConnectionAcceptedNotification.
Now I saw Michael answer .
About the differences between “stream-type” socket and a “datagram” socket type
Do you have iPhone implementation example for native system routines(datagram-socket-type)?
Ok first I found what I needed, with CFSocket API which will allow me to implement UDP Synchronization.
CFSocket API
Sockets are the most basic level of network communications. A socket acts in a similar manner to a telephone jack. It allows you to connect to another socket (either locally or over a network) and send data to that socket.
The most common socket abstraction is BSD sockets. CFSocket is an abstraction for BSD sockets. With very little overhead, CFSocket provides almost all the functionality of BSD sockets, and it integrates the socket into a run loop. CFSocket is not limited to stream-based sockets (for example, TCP), it can handle any type of socket.
You could create a CFSocket object from scratch using the CFSocketCreate function, or from a BSD socket using the CFSocketCreateWithNative function. Then, you could create a run-loop source using the function CFSocketCreateRunLoopSource and add it to a run loop with the function CFRunLoopAddSource. This would allow your CFSocket callback function to be run whenever the CFSocket object receives a message.
Regardless I found AsyncSocket API.
CocoaAsyncSocket supports TCP and UDP. The AsyncSocket class is for TCP, and the AsyncUdpSocket class is for UDP. Each class is described below.
AsyncSocket is a TCP/IP socket networking library that wraps CFSocket and CFStream. It offers asynchronous operation, and a native cocoa class complete with delegate support. Here are the key features:
Queued non-blocking reads and writes, with optional timeouts. You tell it what to read or write, and it will call you when it's done.
Automatic socket acceptance. If you tell it to accept connections, it will call you with new instances of itself for each connection. You can, of course, disconnect them immediately.
Delegate support. Errors, connections, accepts, read completions, write completions, progress, and disconnections all result in a call to your delegate method.
Run-loop based, not thread based. Although you can use it on main or worker threads, you don't have to. It calls the delegate methods asynchronously using NSRunLoop. The delegate methods include a socket parameter, allowing you to distinguish between many instances.
Self-contained in one class. You don't need to muck around with streams or sockets. The class handles all of that.
Support for TCP streams over IPv4 and IPv6.
The library is public domain, originally written by Dustin Voss. Now available in a public setting to allow and encourage its continued support.
AsyncUdpSocket is a UDP/IP socket networking library that wraps CFSocket. It works almost exactly like the TCP version, but is designed specifically for UDP. This includes queued non-blocking send/receive operations, full delegate support, run-loop based, self-contained class, and support for IPv4 and IPv6.
CocoaAsyncSocket
And here is the CFSocket Reference
CFSocket Reference

Emulating accept() for UDP (timing-issue in setting up demultiplexed UDP sockets)

For an UDP server architecture that will have long-lived connections, one architecture is to have one socket that listens to all incoming UDP traffic, and then create separate sockets for each connection using connect() to set the remote address. My question is whether it is possible to do this atomically similar to what accept() does for TCP.
The reason for creating a separate socket and using connect() is that this makes it easy to spread the packet-processing across multiple threads, and also make it easier to have the socket directly associated with the data structures that are needed for processing.
The demultiplexing logic in the networking stack will route the incoming packets to the most specific socket.
Now my question is basically what happens when one wants to emulate accept() for UDP like this:
Use select() with a fd-set that includes the UDP server-socket.
Then read a packet from the UDP server-socket.
Then create a new UDP socket which is then connect()ed to the remote address
I call select() with a fd-set that includes both sockets.
What is returned?
given that a packet arrives to the OS somewhere between 1 and 3.
Will the packet be demultiplexed to the UDP server-socket, or will it be demultiplexed to the more specific socket created in 3. That is, at what point does demultiplexing take place? When the packet arrives, or must it happen "as if" it arrived at point 4?
Follow-up question in case the above does not work: What's the best way to do this?
I see that this discussion is from 2009, but since it keeps popping up when I search, I thought I should share my approach. Both to get some feedback and because I am curios about how the author of the question solved the problem.
The way I chose emulate UDP-accept was a combination of number one and two in nik's answer. I have a root thread which listens on a given socket. I have chosen to use TCP for simplicity, but changing this socket to UDP is not very hard. When a client wants to "connect" to my server using UDP, it first connects to the TCP socket and requests a new connection.
The root thread then proceeds by creating a UDP socket, binds it to a local interface, does connect and sets up data structures. This file descriptor is then passed to the thread that will be responsible for the connection. The IP/port information of the new UDP socket is passed back to the client, which creates a new UDP socket and sends data to the provided IP/port.
This approach works well for my use, but the additional steps for setting up a flow introduces an overhead. In some cases, this overhead might not be acceptable.
I found this question after asking it myself here...
UDP server and connected sockets
Since connect() is available for UDP to specify the peer address, I wonder why accept() wasn't made available to effectively complete the connected UDP session from the server side. It could even move the datagram (and any others from the same client) that triggered the accept() over to the new descriptor.
This would enable better server scalability (see the rationale behind SO_REUSEPORT for more background), as well as reliable DTLS authentication.
This will not work.
You have two simple options.
Create a multi-threaded program that has a 'root' thread listening on the UDP socket and 'dispatching' received packets to the correct thread based on the source. This is because you want to segregate processing by source.
Extend your protocol so the the sources accept an incoming connection on some fixed port and then continue with the protocol communication. In this case you would let the source request on the standard UDP port (of your choice), then your end will respond from a new UDP socket to the sources' UDP port. This way you have initiated a new UDP path from your end backwards to the known UDP port of each source. That way you have different UDP sockets at your end.