socket 程式設計 伺服器端-客戶端
socket 程式設計 伺服器端-客戶端
/****
伺服器端程式碼
*****/
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#define PORT 3339
int main(void)
{
char *sendbuf = "thanks";
char buf[256];
int s_fd, c_fd;
int s_len, c_len;
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
s_fd = socket(AF_INET, SOCK_STREAM, 0);
s_addr.sin_family = AF_INET;
s_addr.sin_addr.s_addr = htonl(INADDR_ANY);
s_addr.sin_port = PORT;
s_len = sizeof(s_addr);
bind(s_fd, (struct sockaddr *)&s_addr,s_len);
listen(s_fd, 10);
while(1)
{
printf("please wait a moment");
c_len = sizeof(c_addr);
c_fd = accept(s_fd,(struct sockaddr *)&c_addr, (socklen_t*__restrict)&c_len);
recv(c_fd,buf,256,0);
buf[sizeof(buf)+1] = '\0';
printf("receive message:\n%s\n",buf);
send(c_fd, sendbuf, sizeof(sendbuf),0);
close(c_fd);
}
return 0;
}
/*****
客戶端程式碼
****/
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#define PORT 3339
int main(void)
{
int sockfd;
int len;
struct sockaddr_in addr;
int newsockfd;
char *buf = "come on!";
int len2;
char rebuf[40];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = PORT;
len = sizeof(addr);
newsockfd = connect(sockfd,(struct sockaddr *)&addr, len);
if(newsockfd == -1)
{
perror("link failed!");
return 1;
}
len2 = sizeof(buf);
send(sockfd, buf, len2, 0);
sleep(10);
recv(sockfd, rebuf, 256, 0);
rebuf[sizeof(rebuf) + 1] = '\0';
printf("receive message :\n%s\n", rebuf);
close(sockfd);
return 0;
}