Laboratoriya ish – 9 Mavzu: Tarmoqda (Socket ) C++ tilida dasturlash


Download 62.46 Kb.
Sana06.05.2023
Hajmi62.46 Kb.
#1434723
Bog'liq
9-laboratoriya ishi

LABORATORIYA ISH – 9

Mavzu: Tarmoqda (Socket ) C++ tilida dasturlash.


Ishning maqsadi: Linux operatsion tizimida soket interfeysi mavjud bo’lib, u orqali dasturlar boshqa kompyuterdagi dasturlar bilan o’zaro muvofiq aloqa o’rnatishi mumkin, bu esa klient-server ilovalar yaratishda qo’l keladi.
ASOSIY QISM
Bu interfeys Windows operatsion tizimidagi Windows Sockets yoki WinSock spetsifikatsiyasi yordami bilan mavjuddir. Socketlar yordamida Linux va Unix oilasidagi operatsion tizimlar bir-birovi bilan aloqa qilishi mumkin. Lekin WinSock bilan to’liq muvofiqlik yo’q.
AMALIY QISM
Quyida klient-server dasturini ko’rib chiqamiz. Ushbu dasturda klient qismdan klientdan so’rovni kutib turgan serverga xabar yobramiz, u biz yuborgan xabarga qo’shimcha qo’shib klientga qaytarib yuboradi.
Server qism:
#include
#include
#include
#include
#include
#include
int main() {
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_un server_address;
struct sockaddr_un client_address;
unlink("server_socket");
server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, "server_socket");
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
listen(server_sockfd, 5);
while(1) {
char ch[20];
printf("Client kutib turibman seni:\n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,
(struct sockaddr *)&client_address, &client_len);
read(client_sockfd, &ch, 20);
strcpy(ch+5," louser");
write(client_sockfd, &ch, 20);
close(client_sockfd);
}
}
Klient qism:
#include
#include
#include
#include
#include
#include
int main() {
int sockfd;
int len;
struct sockaddr_un address;
int result;
char ch[20] = "Hello";
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
address.sun_family = AF_UNIX;
strcpy(address.sun_path, "server_socket");
len = sizeof(address);
result = connect(sockfd, (struct sockaddr *)&address, len);
if (result == -1) {
perror("Serverga ulanishda xatolik");
exit(1);
}
write(sockfd, &ch, 20);
read(sockfd, &ch, 20);
printf("Serverdan yuborilgan javob = %s\n", ch);
close(sockfd);
exit(0);
}

Klient serverga “Hello” satrini yubordi va server uni qabul qilib “Hello louser” satrini klientga qaytarib yubordi.
Download 62.46 Kb.

Do'stlaringiz bilan baham:




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling