2017年4月22日 星期六

Linux Socket Programming 訊息傳遞程式範例

  • 下圖為建立socket大致上的流程



  • 以下為簡單socket傳遞訊息範例程式碼,先開啟server等待client連線,client連線上後會傳送"Client send a message!"的訊息,當server收到訊息後會回傳"Server reply a message!"的訊息,client接收到訊息後關閉socket,接下來server的socket也關閉。
server程式

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int main(void){
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sockfd, tempsock, port=5566;
socklen_t sin_size;
char message[100];
//TCP socket
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket");
exit(1);
}
//Initial bind to port 5566
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&(my_addr.sin_zero), 8);
//Reuse addr & binding
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &my_addr, sizeof(struct sockaddr));
if(bind(sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == 1){
perror("bind");
exit(1);
}
//Start listening
if(listen(sockfd, 10) == -1){
perror("listen");
exit(1);
}

//Connect
if((tempsock = accept(sockfd, (struct sockaddr*)&their_addr, &sin_size)) == -1){
perror("accept");
exit(1);
}
//Recieving message
recv(tempsock, message, 100, 0);
printf("%s\n",message);

//Sending message
strcpy(message, "Server reply a message!");
send(tempsock, message, 100, 0);

//Close socket
close(tempsock);
return 0;
}

client程式

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int main(void){
struct sockaddr_in address;
int sockfd, port=5566;
char message[100];

//TCP socket
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket");
exit(1);
}

//Initial connect to port 5566
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = inet_addr("127.0.0.1");
bzero(&(address.sin_zero), 8);

//Connect to server
if(connect(sockfd, (struct sockaddr*)&address, sizeof(struct sockaddr)) == -1){
perror("connect");
exit(1);
}

//Sending message
strcpy(message, "Client send a message!");
send(sockfd, message, 100, 0);

//Recieving message
recv(sockfd, message, 100, 0);
printf("%s\n",message);

//Close socket
close(sockfd);
return 0;

}

執行結果
server:
kent@ubuntu:~/socket$ ./server
Client send a message!

client:
kent@ubuntu:~/socket$ ./client
Server reply a message!