Dialog via created sockets

In C language:

Once the connection has been established between the client and the server, there is a two-way communication channel identifiable by the IP addresses and TCP port of each of its ends. On each side, we can write or read in its socket via the write and read functions of the unistd.h library (as we would for a single file).

Writing

The write function takes 3 parameters:

The function returns an integer:

Reading

The read function is a blocking function (i.e. it waits until there is something to read) which takes 3 parameters:

The function returns an integer:

Closing

The shutdown function takes 2 parameters:

The close function takes 1 parameter:

Example:

void customer_dialog(int fd) {
	char buf[256];
	while ((len=read(fd,&buf,sizeof(buf)-1)) != 0) {
		if (len > 0) {
			buf[len]=0x00;
			printf("%s\n",buf);
		} else if (len != EINTR) {
			printf("Socket read error!\n");
			exit(1);
		}
	}
	close(fd);
}
	

void server_dialog(int fd) {
	char msg[] = "Hello customer.\nI'm the server!\n";
	int i, j, l, m=5;

	l=strlen(msg);
	for (i = 0; i < l ; i+=j ){
		j=l-i;
		j=write(fd, &msg[i], (j<m)?j:m);
		if (j < 0 && j != EINTR) {
			printf("Socket write error!\n");
			exit(1);
		}
	}
}
	

PHP and Python:

In languages like PHP or Python, there are libraries interfacing with system functions.

PHP

The example code written in C becomes in PHP:

function customer_dialog($socket) {
	$m=5;
	while (true) {
		$buf = socket_read($socket,$m);
		if ($buf == '') break;
		if ($buf == false) {
			echo "Erreur lecture socket !\n";
			exit(1);
		}
		echo $buf;
	}
}
	

function customer_dialog($socket) {
	$msg="Hello customer.\nI'm the server!\n";
	socket_write($socket,$msg);
}
	

Python

The example code written in C becomes in Python:

def communication_client(sock) :
	try :
		m=5
		while (True) :
			buf=sock.recv(m)
			if (buf =='') :
				break
			print(buf,end='')
	except socket.error :
		print("Error accepting incoming connection!")
		exit()
	

def server_dialog(sock) :
	msg="Hello customer.\nI'm the server!\n"
	sock.send(msg)