소켓 프로그래밍 기본 흐름 - Socket Programming Basic Flow

31433 
Created at 2007-07-16 20:30:09 
303   0   0   0  
소켓을 활용한 프로그래밍에 있어서 Client/Server간의 구조를 아는것도 중요하지만
socket관련함수를 어떻게 사용하는지 아는것도 매우 중요한것 같다.

다음의 도표는 이를 알기 쉽게 표현한 것이다.

소켓 프로그래밍 기본 흐름 - Socket Programming Basic Flow

예제 코드를 보면 좀더 이해가 빠르지 않을까...!?

socket_server.c

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>

#define NSTRS 3 /* no. of strings */
#define ADDRESS "mysocket" /* addr to connect */

/*
* Strings we send to the client.
*/
char *strs[NSTRS] = {
"This is the first string from the server. ",
"This is the second string from the server. ",
"This is the third string from the server. "
};

main()
{
char c;
FILE *fp;
int fromlen;
register int i, s, ns, len;
struct sockaddr_un saun, fsaun;

/*
* Get a socket to work with. This socket will
* be in the UNIX domain, and will be a
* stream socket.
*/
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
perror("server: socket");
exit(1);
}

/*
* Create the address we will be binding to.
*/
saun.sun_family = AF_UNIX;
strcpy(saun.sun_path, ADDRESS);

/*
* Try to bind the address to the socket. We
* unlink the name first so that the bind won't
* fail.
*
* The third argument indicates the "length" of
* the structure, not just the length of the
* socket name.
*/
unlink(ADDRESS);
len = sizeof(saun.sun_family) + strlen(saun.sun_path);

if (bind(s, &saun, len) < 0) {
perror("server: bind");
exit(1);
}

/*
* Listen on the socket.
*/
if (listen(s, 5) < 0) {
perror("server: listen");
exit(1);
}

/*
* Accept connections. When we accept one, ns
* will be connected to the client. fsaun will
* contain the address of the client.
*/
if ((ns = accept(s, &fsaun, &fromlen)) < 0) {
perror("server: accept");
exit(1);
}

/*
* We'll use stdio for reading the socket.
*/
fp = fdopen(ns, "r");

/*
* First we send some strings to the client.
*/
for (i = 0; i < NSTRS; i++)
send(ns, strs[i], strlen(strs[i]), 0);

/*
* Then we read some strings from the client and
* print them out.
*/
for (i = 0; i < NSTRS; i++) {
while ((c = fgetc(fp)) != EOF) {
putchar(c);

if (c == ' ')
break;
}
}

/*
* We can simply use close() to terminate the
* connection, since we're done with both sides.
*/
close(s);

exit(0);
}

socket_client.c

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>

#define NSTRS 3 /* no. of strings */
#define ADDRESS "mysocket" /* addr to connect */

/*
* Strings we send to the server.
*/
char *strs[NSTRS] = {
"This is the first string from the client. ",
"This is the second string from the client. ",
"This is the third string from the client. "
};

main()
{
char c;
FILE *fp;
register int i, s, len;
struct sockaddr_un saun;

/*
* Get a socket to work with. This socket will
* be in the UNIX domain, and will be a
* stream socket.
*/
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
perror("client: socket");
exit(1);
}

/*
* Create the address we will be connecting to.
*/
saun.sun_family = AF_UNIX;
strcpy(saun.sun_path, ADDRESS);

/*
* Try to connect to the address. For this to
* succeed, the server must already have bound
* this address, and must have issued a listen()
* request.
*
* The third argument indicates the "length" of
* the structure, not just the length of the
* socket name.
*/
len = sizeof(saun.sun_family) + strlen(saun.sun_path);

if (connect(s, &saun, len) < 0) {
perror("client: connect");
exit(1);
}

/*
* We'll use stdio for reading
* the socket.
*/
fp = fdopen(s, "r");

/*
* First we read some strings from the server
* and print them out.
*/
for (i = 0; i < NSTRS; i++) {
while ((c = fgetc(fp)) != EOF) {
putchar(c);

if (c == ' ')
break;
}
}

/*
* Now we send some strings to the server.
*/
for (i = 0; i < NSTRS; i++)
send(s, strs[i], strlen(strs[i]), 0);

/*
* We can simply use close() to terminate the
* connection, since we're done with both sides.
*/
close(s);

exit(0);
}



Tags: client server socket 서버 소켓 소켓프로그래밍 윈도우즈 클라이언트 Share on Facebook Share on X

◀ PREVIOUS
Java로 구현하는 간단한 Client & Server 프로그램
▶ NEXT
소켓을 생성하여 CSocket에 Attach하는 방법
  Comments 0
Login for comment
SIMILAR POSTS

간단한 소켓 클라이언트 프로그램 (created at 2007-07-16)

Java로 구현하는 간단한 Client & Server 프로그램 (created at 2007-07-16)

소켓을 생성하여 CSocket에 Attach하는 방법 (created at 2007-07-19)

MFC에서 디스크 포멧(Disk Format)하기 (created at 2007-07-20)

PC 부팅할때 Num Lock 키 해제하는 방법 (created at 2007-07-21)

OWL(One World Language)의 다른 종류 (created at 2007-07-11)

OWL(One World Language)은 무엇인가? (created at 2007-07-11)

온톨로지(ontology)란 무엇인가? (created at 2007-07-11)

Exchange Server 인증서 때문에 Windows Mobile 디바이스와 ActiveSync가 되지 않는 경우 해결법 (created at 2007-07-24)

듀얼모니터를 쓸때 태스크바가 하나 밖에 없어서 불편했던 사람들을 위한 - 듀얼모니터용 프로그램 울트라몬 (UltraMon) (created at 2007-08-08)

한글을 유니코드 또는 UTF-8포멧으로 변환하는 방법 (created at 2007-08-09)

델파이에서 URL Encoding 하는 방법 (created at 2007-08-09)

쓰기 불편해 XP로 U턴하는 이용자 늘어, 윈도비스타 '징검다리 OS' 되나 (created at 2007-08-09)

비스타에 이은 마이크로소프트 윈도우 차기 버전「윈도우 7」 (created at 2007-08-09)

마이크로소프트 윈도우7 (WIndows 7) 미공개 바탕화면 (created at 2007-08-09)

TComboBox Readonly로 만드는 방법 (created at 2007-08-09)

웹페이지 속도 빠르게 하는 방법 10가지 (created at 2007-06-21)

UTF-8로 인코딩된 문자열을 EUC-KR로 바꾸는 방법 (created at 2007-05-29)

UPnP 네트워크의 예 (created at 2007-05-27)

UPnP 프로토콜 개요 (created at 2007-05-27)

UPnP 네트워크의 구성요소 (created at 2007-05-27)

UPnP의 작동 방법 (created at 2007-05-27)

DLNA, UPnP 개요 (created at 2007-05-27)

원격 부팅(Wake on-LAN : WOL) (created at 2007-05-27)

유즈 케이스(Use Case)를 활용한 UML 표기법 입문 (created at 2007-05-26)

백줄 글보다 낫다「다이어그램 작성 프로그램」 (created at 2007-05-26)

UML은 무엇을 위해 있는 것일까? (created at 2007-05-26)

타임아웃 시간줄이기 (created at 2007-05-18)

XP 윈도우 창 속도 높이기 (created at 2007-05-18)

Windows XP에서 윈도우 창이 뜨는 속도를 높이는 방법 (created at 2007-05-18)

OTHER POSTS IN THE SAME CATEGORY

mysql 백업에서 복구까지 (created at 2007-10-12)

블로그를 쉽게 할 수 있도록 도와주는 블로깅툴 - Windows Live Writer (created at 2007-10-10)

TV없는 거실..라운드형 거실, 평면의 변신 (created at 2007-09-10)

Flash와 PHP를 활용하여 멀티 파일 업로드 구현하는 방법 (created at 2007-08-14)

TComboBox Readonly로 만드는 방법 (created at 2007-08-09)

마이크로소프트 윈도우7 (WIndows 7) 미공개 바탕화면 (created at 2007-08-09)

비스타에 이은 마이크로소프트 윈도우 차기 버전「윈도우 7」 (created at 2007-08-09)

쓰기 불편해 XP로 U턴하는 이용자 늘어, 윈도비스타 '징검다리 OS' 되나 (created at 2007-08-09)

델파이에서 URL Encoding 하는 방법 (created at 2007-08-09)

한글을 유니코드 또는 UTF-8포멧으로 변환하는 방법 (created at 2007-08-09)

듀얼모니터를 쓸때 태스크바가 하나 밖에 없어서 불편했던 사람들을 위한 - 듀얼모니터용 프로그램 울트라몬 (UltraMon) (created at 2007-08-08)

Exchange Server 인증서 때문에 Windows Mobile 디바이스와 ActiveSync가 되지 않는 경우 해결법 (created at 2007-07-24)

PC 부팅할때 Num Lock 키 해제하는 방법 (created at 2007-07-21)

MFC에서 디스크 포멧(Disk Format)하기 (created at 2007-07-20)

소켓을 생성하여 CSocket에 Attach하는 방법 (created at 2007-07-19)

Java로 구현하는 간단한 Client & Server 프로그램 (created at 2007-07-16)

OWL(One World Language)의 다른 종류 (created at 2007-07-11)

OWL(One World Language)은 무엇인가? (created at 2007-07-11)

온톨로지(ontology)란 무엇인가? (created at 2007-07-11)

시간 알아내는 함수 gmtime (created at 2007-06-27)

웹페이지 속도 빠르게 하는 방법 10가지 (created at 2007-06-21)

글자 깜빡이게 하기 (created at 2007-06-05)

PHP에서 URL Open시 에러가 날때 (created at 2007-06-05)

UTF-8로 인코딩된 문자열을 EUC-KR로 바꾸는 방법 (created at 2007-05-29)

UPnP 네트워크의 예 (created at 2007-05-27)

UPnP 프로토콜 개요 (created at 2007-05-27)

UPnP 네트워크의 구성요소 (created at 2007-05-27)

UPnP의 작동 방법 (created at 2007-05-27)

DLNA, UPnP 개요 (created at 2007-05-27)

원격 부팅(Wake on-LAN : WOL) (created at 2007-05-27)

UPDATES

글루코사민 vs. 콘드로이친: 무엇이 더 나은 관절 건강 보조제일까? (created at 2024-04-22)

광주 5·18 민주화운동 알린 테리 앤더슨 前 AP 기자 (created at 2024-04-22)

햄과 소세지가 우리 몸에 일으키는 부작용 (updated at 2024-04-22)

콘드로이친의 염증 감소효과 (updated at 2024-04-22)

코사민 DS - 글루코사민+콘드로이친 복합물이 함유된 퇴행성 관절 건강보조제 (updated at 2024-04-22)

삼겹살 먹을때 환상조합 (created at 2024-04-22)

일본 여중생의 특이한 취향 (created at 2024-04-22)

우리가 먹는 약물이 바꿔버린 생태계 (created at 2024-04-21)

일본에서 그린 상상속의 사무직과 현실속의 사무직 (updated at 2024-04-21)

북한 미대생들이 그린 북한 최고존엄 김정은 (created at 2024-04-21)

입사 후 1년도 되지 않은 회사에서 구조조정에 의한 퇴직 불응에 따른 해고 처리시 대응 가능한 방법 (updated at 2024-04-20)

한고은님의 옛날 사진 (updated at 2024-04-20)

소녀대 - Bye Bye Girl (updated at 2024-04-13)

대한민국 날씨 근황 (created at 2024-04-13)

성일종 인재육성 강조하며 이토 히로부미 언급 - 인재 키운 선례? (updated at 2024-04-13)

일제강점기가 더 살기 좋았을지도 모른다는 조수연 국민의힘 후보 - 친일파? (updated at 2024-04-13)

Marshall Ha님의 샤오미 SU7 시승기 - 테슬라의 일론 머스크님이 긴장할만한 느낌 (updated at 2024-04-09)

윙크하는 귀염둥이 반려견들 (created at 2024-04-08)

달콤 살벌한 고백 (created at 2024-04-08)

북한 최정예 공수부대 훈련 모습 (updated at 2024-04-02)

맛있었던 친구 어머니의 주먹밥이 먹고 싶어요 (created at 2024-04-02)

자리 마음에 안든다고 6급 공무원 패는 농협 조합장 (created at 2024-03-26)

85세 딸 짜장면 사주는 102세 어머니 (created at 2024-03-26)

1990년대 감각파 도둑 (created at 2024-03-26)

치매에 걸린 69살의 브루스 윌리스가 전부인 데미무어를 보고 한 말 (updated at 2024-03-22)

경제는 대통령이 살리는 것이 아닙니다 라던 윤석열대통령 - 상황 안좋아지자 여러 전략을 펼쳤지만, 부작용 속출했던 2024년의 봄 (updated at 2024-03-13)

극빈의 생활을 하고 배운것이 없는 사람은 자유가 뭔지도 모를 뿐 아니라 왜 개인에게 필요한지에 대한 필요성을 못느낀다는 윤석열 대통령 (updated at 2024-03-08)

조선일보를 안본다는 사람들이 말하는 그 이유 - 천황폐하, 전두환 각하, 김일성 장군 만세? (created at 2024-03-07)

광폭타이어를 장착하면 성능이 좋아질거라는 착각 (updated at 2024-03-03)

면허시험장에서 면허갱신하면 하루만에 끝나나? (updated at 2024-03-03)