欢迎使用CSDN-markdown编辑器

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

using namespace std;

define MAXLINE 5

define OPEN_MAX 100

define LISTENQ 20

define SERV_PORT 4800

define INFTIM 1000

char *g_local_addr=”10.12.22.241”;

void setnonblocking(int sock)
{
int opts;
opts=fcntl(sock,F_GETFL);
if (opts<0)
{
perror(“fcntl(sock,GETFL)”);
exit(1);
}
opts = opts|O_NONBLOCK;
if (fcntl(sock,F_SETFL,opts)<0)
{
perror(“fcntl(sock,SETFL,opts)”);
exit(1);
}
}

int main()
{
int i, maxi, listenfd, connfd, sockfd,epfd,nfds;
ssize_t n;
char line[MAXLINE];
socklen_t clilen;

struct epoll_event ev,events[20];

struct sockaddr_in clientaddr;
struct sockaddr_in serveraddr;

listenfd = socket(AF_INET, SOCK_STREAM, 0);
epfd = epoll_create(256);

setnonblocking(listenfd);

ev.data.fd=listenfd;
ev.events=EPOLLIN|EPOLLOUT|EPOLLET;
epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev);

bzero(&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
inet_aton(g_local_addr,&(serveraddr.sin_addr));
serveraddr.sin_port=htons(SERV_PORT);
bind(listenfd,(sockaddr *)&serveraddr, sizeof(serveraddr));

listen(listenfd, LISTENQ);
cout<<" server on ip : "<

}

//client

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

include

using namespace std;

define MAXLINE 80

define SERV_PORT 4800

char *g_local_addr=”10.12.22.241”;

int main(int argc, char *argv[])
{
struct sockaddr_in servaddr;
char buf[MAXLINE];
int sockfd, n;
char *str;

if (argc != 2)
{
fputs(“usage: ./client message\n”, stderr);
exit(1);
}
str = argv[1];

sockfd = socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, g_local_addr, &servaddr.sin_addr);
servaddr.sin_port = htons(SERV_PORT);

connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

write(sockfd, str, strlen(str));
sleep(1);
n = read(sockfd, buf, MAXLINE);
cout<<” read “<

你可能感兴趣的:(网络笔记)