a socket demo

client_socket.c

#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include <netinet/in.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
//socket()
int sock_cli_fd = socket(AF_INET, SOCK_STREAM, 0);//When the second param is SOCK_STREAM, the third param 0 defaultly infers TCP.
printf("sock_cli_fd: %d\n", sock_cli_fd);
if(sock_cli_fd < 0)
    perror("Error in opening socket!\n");

//connect()
struct sockaddr_in addr_serv;//This is serv struct
memset(&addr_serv, 0, sizeof(addr_serv)); //Do not forget memset~
addr_serv.sin_family = AF_INET; //IPV4
addr_serv.sin_addr.s_addr = inet_addr(argv[1]);
addr_serv.sin_port = htons(atoi(argv[2]));
connect(sock_cli_fd, (struct sockaddr*)&addr_serv, sizeof(addr_serv));

//write()
char ch_write[] = "hello, this is client! have a good day!";
write(sock_cli_fd, ch_write, sizeof(ch_write));

//read()
char ch_read[256];
read(sock_cli_fd, ch_read, sizeof(ch_read)-1);//Why sub 1? 
printf("Read From Server: %s\n", ch_read);

system("pause");
printf("Can not pause!");

//close()
close(sock_cli_fd);
return 0;
}

 

server_socket.c

#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include <netinet/in.h>

int main(int argc, char* argv[])
{
char buff[256];
//create server socket
int serv_sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//注意,在linux中socket用int类型表示

//initialize sockaddr_in struct
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET; //IPV4
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
serv_addr.sin_port = htons(atoi(argv[2]));

//bind ip & port
bind(serv_sock_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));//here is serv_addr
//listen
listen(serv_sock_fd, 5);

//accept
struct sockaddr_in cli_addr;
int cli_size = sizeof(cli_addr);
int sock_cli_fd = accept(serv_sock_fd, (struct sockaddr*)&cli_addr, &cli_size);//why need sock_cli? How ZMQ realize? Notice:the third parm is a ptr.
if(sock_cli_fd<0)
   perror("Error in accept!");
printf("sock_cli_fd:%d\n", sock_cli_fd);

//read
memset(buff, 0, sizeof(buff));
int n = read(sock_cli_fd, buff, sizeof(buff)-1);
if(n<0)
    perror("Error in socket read!\n");
printf("Read Content:%s\n", buff);

//write
char chWrite[] = "hello, this is sock_serve, today is sunny!";
n = write(sock_cli_fd, chWrite, sizeof(chWrite));
if(n<0)
    perror("Error in socket write");

getchar();

//close
close(serv_sock_fd);
close(sock_cli_fd);
return 0;
}
posted @ 2020-06-23 00:19  心媛意码  阅读(96)  评论(0编辑  收藏  举报