最近在鼓捣Ubuntu,开始正式学习Socket网络编程。
今晚跟着教程做好了一个echo服务器,还挺有成就感的。
服务器端:echosrv.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ERR_EXIT(m)\
do\
{\
perror(m);\
exit(EXIT_FAILURE);\
}while(0)\
//处理与客户端的通信
void do_service(int conn)
{
char recvbuf[1024];
while(1)
{
memset(recvbuf, 0, sizeof(recvbuf));
int ret = read(conn, recvbuf, sizeof(recvbuf));
if(ret == 0)
{
printf("client close\n");
break;
}
else if(ret == -1)
ERR_EXIT("read error");
fputs(recvbuf,stdout);
write(conn, recvbuf, ret);
}
}
int main()
{
//创建监听套接字
int listenfd;
if((listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
ERR_EXIT("socket error");
//创建服务器地址
struct sockaddr_in srvaddr;
memset(&srvaddr, 0, sizeof(srvaddr));
srvaddr.sin_family = AF_INET;
srvaddr.sin_port = htons(5188);
srvaddr.sin_addr.s_addr = htonl(INADDR_ANY);
//启用REUSEADDR
int on = 1;
if((setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)))<0)
ERR_EXIT("setsockopt error");
//绑定监听套接字
if((bind(listenfd,(struct sockaddr*)&srvaddr, sizeof(srvaddr))) < 0)
ERR_EXIT("bind error");
//开启监听
if((listen(listenfd,SOMAXCONN)) < 0)
ERR_EXIT("listen error");
struct sockaddr_in peeraddr;
socklen_t peerlen = sizeof(peeraddr);
int conn;
//不断创建子进程来处理连接
pid_t pid;
while(1)
{
//接受一个新的连接
if((conn = accept(listenfd,(struct sockaddr*)&peeraddr,&peerlen)) < 0)
ERR_EXIT("accept error");
printf("new connection from %s:%d\n",inet_ntoa(peeraddr.sin_addr),htons(peeraddr.sin_port));
//分叉成两个进程,子进程返回0,父进程返回子进程id
pid = fork();
if(pid == -1)
ERR_EXIT("fork error");
else if(pid == 0)
{
close(listenfd);
do_service(conn);
exit(EXIT_SUCCESS);
}
else
close(conn);
}
return 0;
}
客户端:echoclnt.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ERR_EXIT(m)\
do\
{\
perror(m);\
exit(EXIT_FAILURE);\
}while(0)\
int main()
{
//创建套接字
int sock;
if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
ERR_EXIT("socket error");
//创建服务器地址
struct sockaddr_in srvaddr;
memset(&srvaddr, 0, sizeof(srvaddr));
srvaddr.sin_family = AF_INET;
srvaddr.sin_port = htons(5188);
srvaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
//链接服务器
if(connect(sock,(struct sockaddr*)&srvaddr,sizeof(srvaddr))<0)
ERR_EXIT("connect error");
//处理通信
char sendbuf[1024] = {0};
char recvbuf[1024] = {0};
while((fgets(sendbuf,sizeof(sendbuf),stdin))!=NULL)
{
write(sock,sendbuf,strlen(sendbuf));
read(sock,recvbuf,sizeof(recvbuf));
fputs(recvbuf,stdout);
memset(sendbuf,0,sizeof(sendbuf));
memset(recvbuf,0,sizeof(recvbuf));
}
close(sock);
return 0;
}
另外视频中的老师用的是vi+makefile写的代码,看着真是酷毙了。等学完Socket部分,一定要好好看看makefile的相关知识。