备忘:
## client.c
~~~~~~~~~~~~~~~~~
#include
#include
#include
#include
#include
#include
#include
#define BUF_LEN 1024
#define SERVER_PORT 6789
int main(int argc, char* argv[])
{
int sockfd = 0;
char recvline[BUF_LEN] = {0};
char sendline[BUF_LEN] = {0};
struct sockaddr_in servaddr;
memset(&servaddr, 0x00, sizeof(struct sockaddr_in));
/* check parameter */
if(argc != 2){
printf("usage: ./client \n");
exit(0);
}
/* create socket */
if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){
printf("create socket error! errno = %d\n", errno);
exit(0);
}
/* init server address */
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERVER_PORT);
if( inet_pton(AF_INET, argv[1], &servaddr.sin_addr) == -1){
printf("inet_pton error for %s\n",argv[1]);
exit(0);
}
if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){
printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
exit(0);
}
printf("send msg to server: \n");
/* send message to server*/
fgets(sendline, BUF_LEN, stdin);
if( send(sockfd, sendline, strlen(sendline), 0) == -1)
{
printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
exit(0);
}
close(sockfd);
exit(0);
}
server.c
~~~~~~~~~~~~~~~~~~~~~
#include
#include
#include
#include
#include
#include
#include
#define BUF_LEN 1024
#define SERVER_PORT 6789
int main(int argc, char* argv[])
{
int sockfd = 0;
int connfd = 0;
int recv_len = 0;
char buff[BUF_LEN] = {0};
struct sockaddr_in servaddr;
memset(&servaddr, 0x00, sizeof(struct sockaddr_in));
/* create server's socket */
if( (sockfd= socket(AF_INET, SOCK_STREAM, 0)) == -1 ){
printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);
exit(0);
}
/* init server socket struct */
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERVER_PORT);
if( bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){
printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);
exit(0);
}
if( listen(sockfd, 5) == -1){
printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);
exit(0);
}
printf("## SERVER START\n");
while(1)
{
/* recv client's date */
if( (connfd = accept(sockfd, (struct sockaddr*)NULL, NULL)) == -1)
{
printf("accept socket error: %s(errno: %d)",strerror(errno),errno);
continue;
}
recv_len = recv(connfd, buff, BUF_LEN, 0);
buff[recv_len] = '\0';
printf("recv msg from client: %s\n", buff);
close(connfd);
}
close(sockfd);
}
阅读(6328) | 评论(1) | 转发(0) |