.. index:: 
	single: sockets; Introduction

=====================
RingSockets Extension
=====================

In this chapter we will learn about using the RingSockets extension.

.. index:: 
	pair: sockets; TCP Server

TCP Server
==========

Example (TCP Server Code): 

.. code-block:: ring

	load "sockets.ring" 

	sock = socket(AF_INET,SOCK_STREAM,0) 
	bind(sock,"127.0.0.1",5050)
	listen(sock,5)
	ns = accept(sock)

	send(ns,"Hello Client")
	msg = recv(ns,1024)
	? "Client Say >> " + msg
	close(ns)
	close(sock)
	? "socket connection closed"

.. index:: 
	pair: sockets; TCP Client

TCP Client
==========

Example (TCP Client Code):

.. code-block:: ring

	load "sockets.ring" 

	sock = socket(AF_INET,SOCK_STREAM)
	connect(sock,"127.0.0.1",5050)

	send(sock,"Hello Server")
	msg = recv(sock,1024)
	? "Server Say >> " + msg

	close(sock)
	? "socket connection closed"

.. index:: 
	pair: sockets; Functions

Functions
=========

The next functions are provided by this extension

.. code-block:: none

	socket(nAddressFamily, nConnectionType) -> SocketHandle
	bind(pSocketHandle, cHost , nPort)
	listen(pSocketHandle, nBacklog)
	accept(pSocketHandle) -> pConnectionHandle
	send(pConnectionHandle|pSocketHandle,cMessage)
	sendto(pSocketHandle,cMessage)
	recv(pConnectionHandle|pSocketHandle,nBuffer) -> cData
	recvfrom(pSocketHandle, nBuffer) -> cData
	connect(pSocketHandle, cHost , nPort) -> return <0> if successful
	close(pSocketHandle|pConnectionHandle)
	gethostbyname(cHostName) -> cIPAddress
	gethostbyaddr(cIPAddress) -> aListOfHostInfo
	gethostname() -> cHostName
	getservbyname(cName) -> nPort
	getservbyport(nPort) -> cName

Example:

.. code-block:: ring

	load "sockets.ring"

	host = gethostbyname("google.com")
	? host
	line()
	? gethostbyaddr(host)
	line()
	? gethostname()
	line()
	? getservbyname("ftp")
	line()
	? getservbyport(21)

	func line ? copy("=",30)

.. index:: 
	pair: socket; Constants

Constants
=========

Address Family:

.. code-block:: none   

	AF_INET       #  mean use IPV4
	AF_INET6      #  ........ IPV6

Connection type:

.. code-block:: none   

	SOCK_STREAM   #  mean use TCP Protocol
	SOCK_DGRAM    #  ........ UDP ........
