Presentation is loading. Please wait.

Presentation is loading. Please wait.

Socket 程式設計.

Similar presentations


Presentation on theme: "Socket 程式設計."— Presentation transcript:

1 Socket 程式設計

2 Outline Introduction Function Call Design

3 Introduction (cont.) TCP UDP TCP是一個連結協定,透過TCP可確保接收端收到完整、正確的資料

4 Introduction (cont.) “Socket” 是一種可做雙向資料傳輸的通道,可經由此與 local 或是 remote 的程式做溝通。 Socket local socket:主要用來與本地端的程序溝通 internet-domain socket:用來與遠地端的程序溝通

5 Outline Introduction Function Call Design

6 Function Call IPv4 socket定址結構 struct sockaddr_in {
    sa_family_t sin_family;            unsigned short int sin_port;     struct in_addr sin_addr;     }; 結構成員 說明 sin_family 用來說明socket所使用的定址模式,在此必須設為AF_INET,表示internet domain的socket。 sin_port 用來表示TCP/IP的port umber,設定sin_port必需使用htons函數作位元排序的動作。 sin_addr 是一個in_addr的結構變數,用來表示ip位址。

7 Function Call (cont.) IPv4 socket定址結構 Ex:
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> struct sockaddr_in adr_srvr; adr_srvr.sin_family = AF_INET; adr_srvr.sin_addr.s_addr = inet_addr(" "); //adr_srvr.sin_addr.s_addr = inet_addr(INADDR_ANY); adr_srvr.sin_port = htons(8000);

8 Function Call (cont.) int socket(int domain, int type, protocol);
不論是TCP或UDP作為傳輸協定,都要透過socket作資料傳輸,首要工作是先建立socket int socket(int domain, int type, protocol); 引數 說明 domain 設定為AF_INET表示internet協定 type 連結的型態。 設定為SOCK_STRREAM表示TCP傳輸層協定。 設定為SOCK_DGRAM表示UCP傳輸層協定。 protocol 通訊協定,一般為0,表示自動選擇。

9 Function Call (cont.) socket() 傳回值: 成功:傳回socket ID。 失敗:傳回-1。 Ex:
#include <sys/types.h> #include <sys/socket.h> Int sockfd; sockfd = Socket(AF_INET, SOCK_STREAM, 0); 傳回值: 成功:傳回socket ID。 失敗:傳回-1。

10 Function Call (cont.) port type 說明 20 TCP FTP - data port Official 21
FTP - control (command) port Official 22 SSH (Secure Shell) - used for secure logins, file transfers (scp, sftp) and port forwarding Official 23 Telnet protocol - unencrypted text communications Official 25 SMTP - used for routing between mailservers s Official 53 DNS (Domain Name System) Official 80 HTTP (HyperText Transfer Protocol) - used for transferring web pages Official HTTP - HTTP listening port Official 110 POP3 (Post Office Protocol version 3) - used for sending/retrieving s 137 NetBIOS NetBIOS Name Service Official 138 NetBIOS NetBIOS Datagram Service Official 139 NetBIOS NetBIOS Session Service Official

11 Function Call (cont.) port type 說明 20 UDP FTP - data port Official 21
FTP - control (command) port Official 22 SSH (Secure Shell) - used for secure logins, file transfers (scp, sftp) and port forwarding Official 23 Telnet protocol - unencrypted text communications Official 25 SMTP - used for routing between mailservers s Official 53 DNS (Domain Name System) Official 67 BOOTP (BootStrap Protocol) server; also used by DHCP (Dynamic Host Configuration Protocol) Official 137 NetBIOS NetBIOS Name Service Official 138 NetBIOS NetBIOS Datagram Service Official 139 NetBIOS NetBIOS Session Service Official

12 Function Call (cont.) 將IPv4 socket定址結構連結到所建立的socket
int bind(int sockfd, const struct sockaddr *my_addr, size_t adr_len); 引數 說明 sockfd socket函數執行後傳回的socket ID my_addr 指向socket sockaddr_in結構的指標,用來存放連結的IPv4定址結構 adr_len struct sockaddr_in結構的長度,可將其指定為sizeof(struct sockaddr_in)

13 Function Call (cont.) bind() Ex: #include <sys/socket.h>
bind(sockfd, (struct sockaddr*)&adr_srvr, sizeof(struct sockaddr)); 傳回值: 成功:傳回 0。 失敗:傳回-1。

14 Function Call (cont.) 等待client端的連線要求,會把連線請求放在連線佇列中
int listen(int sockfd, int backlog); 引數 說明 sockfd socket函數執行後傳回的socket ID backlog 指定最大連線的數量,通常為5

15 Function Call (cont.) listen() Ex: #include <sys/socket.h>
Int num = 5; listen(sockfd, num); 傳回值: 成功:傳回 0。 失敗:傳回-1。

16 Function Call (cont.) 呼叫accept函數來處理並接受佇列中的連線請求
int accept(int socketfd, struct sockaddr *addr, socklen_t addrlen); 引數 說明 sockfd socket函數執行後傳回的socket ID addr 指向struct sockaddr_in結構的指標,用來存放client端的IP address addrlen 存放client IP address變數的長度,初值為sizeof(struct sockaddr_in),accept()執行成功後會回存實際的client ip address長度。

17 Function Call (cont.) accept() Ex: #include <sys/socket.h>
accept(sockfd, (struct sockaddr*)&adr_srvr, (struct sockaddr*)&sizeof(adr_srvr)); 傳回值: 成功:傳回client的socket ID,稱為connect socket 。 失敗:傳回-1。

18 Function Call (cont.) 用connect()函數向server端要求建立連線
int connect(int sockfd, struct sockaddr *serv_addr, int addrlen); 引數 說明 sockfd socket函數執行後傳回的socket ID serv_addr 指向struct sockaddr_in結構的指標,用來存放server的address1 addrlen struct sockaddr_in結構的長度,可指定為sizeof(struct sockaddr_in)

19 Function Call (cont.) connect() Ex: #include <sys/socket.h>
connect(sockfd, (struct sockaddr*)&adr_srvr, (struct sockaddr*)&sizeof(adr_srvr)); 傳回值: 成功:傳回 0。 失敗:傳回-1。

20 Function Call (cont.) 將資料寫入已經開啟的socket
int write(int sockfd, char *buf, int len); 引數 說明 sockfd socket函數執行後傳回的socket ID buf 指向字元暫存器的指標,用來存放讀取到的資料 len 欲讀取的字元長度。

21 Function Call (cont.) write() Ex: #include <sys/socket.h>
Char buf[MAX_PATH] = “HelloWorld”; write(sockfd, buf, sizeof(buf)); 傳回值: 成功:傳回寫入的字元數。 失敗:傳回-1。

22 Function Call (cont.) 從已經開啟的socket讀取資料
int read(int sockfd, char *buf, int len); 引數 說明 sockfd socket函數執行後傳回的socket ID buf 指向字元暫存器的指標,用來存放讀取到的資料 len 欲讀取的字元長度。

23 Function Call (cont.) read() Ex: #include <sys/socket.h>
Char buf[MAX_PATH]; read(sockfd, buf, sizeof(buf)); 傳回值: 成功:傳回接收的字元數。 失敗:傳回-1。

24 Function Call (cont.) 從已經開啟的socket傳送資料
int send(int sockfd, const void *msg, int len, unsigned int flags); flags 引數 說明 MSG_OOB 接收的資料以out-of-band送出 MSG_DONTROUTE 取消route的查詢 MSG_DONTWAIT 傳送過程不可以被阻斷 MSG_NOSIGNAL 傳送動作不會因SIGPIPE訊號中斷

25 Function Call (cont.) send() Ex: #include <sys/types.h>
#include <sys/socket.h> Char buf[MAX_PATH] = “HelloWorld”; send(sockfd, buf, sizeof(buf), 0); 傳回值: 成功:傳回傳送的字元數。 失敗:傳回-1。

26 Function Call (cont.) 從已經開啟的socket接收資料
int recv(int sockfd, const void *msg, int len, unsigned int flags); flags 引數 說明 MSG_OOB 接收以out-of-band送來的資料 MSG_PEEK 遠端socket傳來的資料,不會在接收受刪除 MSG_WAITALL 固定接收len引數指定長度的資料,除非有錯誤或訊號發生 MSG_NOSIGNAL 接收動作不會因SIGPIPE訊號中斷

27 Function Call (cont.) recv() Ex: #include <sys/types.h>
#include <sys/socket.h> Char buf[MAX_PATH]; recv(sockfd, buf, sizeof(buf), 0); 傳回值: 成功:傳回接收的字元數。 失敗:傳回-1。

28 Function Call (cont.) 呼叫close()終止client端和server端的連線。
int close(int sockfd); 引數 說明 sockfd socket函數執行後傳回的socket ID

29 Function Call (cont.) close() Ex: #include <unistd.h>
int close(int sockfd); 傳回值: 成功:傳回 0。 失敗:傳回-1。

30 Outline Introduction Function Call Design

31 Design 設計tcp網路程式 TCP client端 TCP server端 1.建立socket(使用socket()函數)
2.向server要求連線(使用connect()函數) 3.若連線成功,使用輸出入函數和server端互傳訊息 4.關閉socket,結束連線(使用close()函數) TCP server端 2.連結socket(使用bind()函數) 3.開啟listening socket(使用listen()函數) 4.等待client連線要求(使用accept()函數) 5.若連線成功,使用輸出入函數和client端互傳訊息 6.關閉socket,結束連線(使用close()函數)

32 Design (cont.) TCP程式設計流程

33 Client - Server Communication - Unix
Stream (e.g. TCP) Datagram (e.g. UDP) Server Client Server Client socket() socket() socket() socket() bind() bind() bind() listen() synchronization point accept() connect() recv() send() recvfrom() sendto() send() recv() sendto() recvfrom() close() close() close() close() Tutorial by Eleftherios Kosmas CS556 - Distributed Systems

34 Exchanging data with stream socket
int count = send(sockid, msg, msgLen, flags); Q msg: const void[], message to be transmitted Q msgLen: integer, length of message (in bytes) to transmit Q flags: integer, special options, usually just 0 Q count: # bytes transmitted (-1 if error) int count = recv(sockid, recvBuf, bufLen, flags); Q recvBuf: void[], stores received bytes Q bufLen: # bytes received Q count: # bytes received (-1 if error) Calls are blocking Q returns only after data is sent / received CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

35 Exchanging data with datagram socket
int count = sendto(sockid, msg, msgLen, flags, &foreignAddr, addrlen); Q msg, msgLen, flags, count: same with send() Q foreignAddr: struct sockaddr, address of the destination Q addrLen: sizeof(foreignAddr) int count = recvfrom(sockid, recvBuf, bufLen, flags, &clientAddr, addrlen); Q recvBuf, bufLen, flags, count: same with recv() Q clientAddr: struct sockaddr, address of the client Q addrLen: sizeof(clientAddr) Calls are blocking Q returns only after data is sent / received CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

36 CS556 - Distributed Systems
Example - Echo A client communicates with an “echo” server The server simply echoes whatever it receives back to the client CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

37 Example - Echo using stream socket
The server starts by getting ready to receive client connections… Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

38 Example - Echo using stream socket
/* Create socket for incoming connections */ if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

39 Example - Echo using stream socket
echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoServAddr.sin_port = htons(echoServPort); /* Local port */ if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("bind() failed"); Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

40 Example - Echo using stream socket
/* Mark the socket so it will listen for incoming connections */ if (listen(servSock, MAXPENDING) < 0) DieWithError("listen() failed"); Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

41 Example - Echo using stream socket
for (;;) /* Run forever */ { clntLen = sizeof(echoClntAddr); if ((clientSock=accept(servSock,(struct sockaddr *)&echoClntAddr,&clntLen))<0) DieWithError("accept() failed"); ... Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

42 Example - Echo using stream socket
Server is now blocked waiting for connection from a client A client decides to talk to the server Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

43 Example - Echo using stream socket
/* Create a reliable, stream socket using TCP */ if ((clientSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

44 Example - Echo using stream socket
echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = inet_addr(echoservIP); /* Server IP address*/ echoServAddr.sin_port = htons(echoServPort); /* Server port */ if (connect(clientSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("connect() failed"); Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: Client Create a TCP socket Establish connection Communicate Close the connection 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

45 Example - Echo using stream socket
Server’s accept procedure in now unblocked and returns client’s socket for (;;) /* Run forever */ { clntLen = sizeof(echoClntAddr); if ((clientSock=accept(servSock,(struct sockaddr *)&echoClntAddr,&clntLen))<0) DieWithError("accept() failed"); ... Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: Client Create a TCP socket Establish connection Communicate Close the connection 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

46 Example - Echo using stream socket
echoStringLen = strlen(echoString); /* Determine input length */ /* Send the string to the server */ if (send(clientSock, echoString, echoStringLen, 0) != echoStringLen) DieWithError("send() sent a different number of bytes than expected"); Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

47 Example - Echo using stream socket
/* Receive message from client */ if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) DieWithError("recv() failed"); /* Send received string and receive again until end of transmission */ while (recvMsgSize > 0) { /* zero indicates end of transmission */ if (send(clientSocket, echobuffer, recvMsgSize, 0) != recvMsgSize) DieWithError(“send() failed”); if ((recvMsgSize = recv(clientSocket, echoBuffer, RECVBUFSIZE, 0)) < 0) DieWithError(“recv() failed”); } Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

48 Example - Echo using stream socket
Similarly, the client receives the data from the server Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

49 Example - Echo using stream socket
close(clientSock); close(clientSock); Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection Tutorial by Eleftherios Kosmas CS556 - Distributed Systems

50 Example - Echo using stream socket
Server is now blocked waiting for connection from a client Client Create a TCP socket Establish connection Communicate Close the connection Server Create a TCP socket Assign a port to socket Set socket to listen Repeatedly: 1. 1. 2. 2. 3. 3. 4. 4. Accept new connection Communicate Close the connection CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

51 Example - Echo using datagram socket
/* Create socket for sending/receiving datagrams */ if ((servSock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed"); /* Create a datagram/UDP socket */ if ((clientSock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) DieWithError("socket() failed"); Server Create a UDP socket Assign a port to socket Repeatedly Communicate Client Create a UDP socket Assign a port to socket Communicate Close the socket 1. 1. 2. 2. 3. 3. 4. CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

52 Example - Echo using datagram socket
echoServAddr.sin_family = AF_INET; /* Internet address family */ echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoServAddr.sin_port = htons(echoServPort); /* Local port */ if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("bind() failed"); echoClientAddr.sin_family = AF_INET; /* Internet address family */ echoClientAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ echoClientAddr.sin_port = htons(echoClientPort); /* Local port */ if(bind(clientSock,(struct sockaddr *)&echoClientAddr,sizeof(echoClientAddr))<0) DieWithError("connect() failed"); Client Create a UDP socket Assign a port to socket Communicate Close the socket Server Create a UDP socket Assign a port to socket Repeatedly Communicate 1. 1. 2. 2. 3. 3. 4. CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

53 Example - Echo using datagram socket
echoServAddr.sin_family = AF_INET; echoServAddr.sin_addr.s_addr = inet_addr(echoservIP); echoServAddr.sin_port = htons(echoServPort); /* Internet address family */ /* Server IP address*/ /* Server port */ echoStringLen = strlen(echoString); /* Determine input length */ /* Send the string to the server */ if (sendto( clientSock, echoString, echoStringLen, 0, (struct sockaddr *) != echoStringLen) DieWithError("send() sent &echoServAddr, sizeof(echoServAddr)) a different number of bytes than expected"); Client Create a UDP socket Assign a port to socket Communicate Close the socket Server Create a UDP socket Assign a port to socket Repeatedly Communicate 1. 1. 2. 2. 3. 3. 4. CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

54 Example - Echo using datagram socket
for (;;) /* Run forever */ { clientAddrLen = sizeof(echoClientAddr) /* Set the size of the in-out parameter */ /*Block until receive message from client*/ if ((recvMsgSize = recvfrom(servSock, echoBuffer, ECHOMAX, 0), (struct sockaddr *) &echoClientAddr, sizeof(echoClientAddr))) < 0) DieWithError(“recvfrom() failed"); if (sendto(servSock, echobuffer, recvMsgSize, 0, (struct sockaddr *) &echoClientAddr, sizeof(echoClientAddr)) != recvMsgSize) DieWithError(“send() failed”); } Client Create a UDP socket Assign a port to socket Communicate Close the socket Server Create a UDP socket Assign a port to socket Repeatedly Communicate 1. 1. 2. 2. 3. 3. 4. CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

55 Example - Echo using datagram socket
Similarly, the client receives the data from the server Client Create a UDP socket Assign a port to socket Communicate Close the socket Server Create a UDP socket Assign a port to socket Repeatedly Communicate 1. 1. 2. 2. 3. 3. 4. CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

56 Example - Echo using datagram
socket close(clientSock); Client Create a UDP socket Assign a port to socket Communicate Close the socket Server Create a UDP socket Assign a port to socket Repeatedly Communicate 1. 1. 2. 2. 3. 3. 4. CS556 - Distributed Systems Tutorial by Eleftherios Kosmas

57 Client - Server Communication - Unix
Stream (e.g. TCP) Datagram (e.g. UDP) Server Client Server Client socket() socket() socket() socket() bind() bind() bind() listen() synchronization point accept() connect() recv() send() recvfrom() sendto() send() recv() sendto() recvfrom() close() close() close() close() Tutorial by Eleftherios Kosmas CS556 - Distributed Systems


Download ppt "Socket 程式設計."

Similar presentations


Ads by Google