服务器:
//服务器 #include <stdio.h> #include <netinet/in.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <errno.h> #include <string.h> int main() { struct sockaddr_in serverAddr,clientAddr;//保存网络地址信息的结构体 memset (&serverAddr,0,sizeof(serverAddr)); serverAddr.sin_family = AF_INET;//协议族/地址族 serverAddr.sin_port = htons(atoi("8080"));//保存端口号 atoi(字符串->整形"8080"->8080) serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//IP地址 int listenFd = socket (AF_INET,SOCK_STREAM,0);//创建套接字 //绑定本地地址和端口 int ret = bind (listenFd,(struct sockaddr*)&serverAddr,sizeof(serverAddr)); ret = listen(listenFd,100);//监听
int clientFd; int cliLen = sizeof (clientAddr);
while(1){ clientFd = accept(listenFd,(struct sockaddr*)&clientAddr,&cliLen);//接收数据,阻塞 char buff[1024] = {0}; ret = read(clientFd,buff,1024); printf ("recv a msg:%s\n",buff);
close (clientFd); } close (listenFd); return 0; }
客户端:
//客户端 #include <stdio.h> #include <netinet/in.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <errno.h> #include <string.h> int main() { struct sockaddr_in serverAddr; memset (&serverAddr,0,sizeof(serverAddr)); serverAddr.sin_family = AF_INET;//协议族 serverAddr.sin_port = htons(atoi("8080"));//端口号 serverAddr.sin_addr.s_addr = inet_addr ("127.0.0.1");//IP地址 int fd = socket(AF_INET,SOCK_STREAM,0);//创建套接字 //链接服务器 int ret = connect(fd,(struct sockaddr*)&serverAddr,sizeof(serverAddr)); // socket描述符, 服务器地址, socket结构体长度 char buff[1024]={0}; ret = read(0,buff,1024); ret = write(fd,buff,ret-1);//去掉回车 // printf ("send a msg :hello\n"); close(fd); return 0; }