服务端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>int main()
{//监听套接字文件描述符int listenFd = -1;//连接套接字的文件描述符int connFd = -1;//服务器的地址结构struct sockaddr_in servAddr = {0};//客户端的地址结构struct sockaddr_in cliAddr = {0};socklen_t len = sizeof(cliAddr);int ret;char buf[100] = {0};//创建套接字listenFd = socket(PF_INET, SOCK_STREAM, 0);if(listenFd < 0){perror("socket error!\n");return -1;}printf("socket ok!\n");//绑定ip地址和端口号servAddr.sin_family = PF_INET;servAddr.sin_port = htons(10086);servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");ret = bind(listenFd, (struct sockaddr *)&servAddr, sizeof(servAddr));if(ret < 0){perror("bind error!");close(listenFd);return -1;}printf("bind ok!\n");//创建监听队列(使得主动的套接字变成可以被连接的被动套接字)ret = listen(listenFd, 1);if(ret < 0){perror("listen error");close(listenFd);return -1;}printf("listening....\n");//等待并建立连接connFd = accept(listenFd, (struct sockaddr *)&cliAddr, &len);if(connFd < 0){perror("accept error!");close(listenFd);return -1;}printf("IP:%s,PORT:%d accept ok!\n", inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port));//接收消息并打印ret = recv(connFd, buf, sizeof(buf), 0);if(ret < 0){perror("recv error!");close(listenFd);close(connFd);return -1;}printf("recv:%s\n", buf);//关闭套接字sleep(4);close(listenFd);close(connFd);return 0;
}
客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>int main()
{int sockFd = -1;//服务器的地址结构struct sockaddr_in servAddr = {0};int ret;char buf[100] = "aaaaaaaaa";//创建套接字sockFd = socket(PF_INET, SOCK_STREAM, 0);if(sockFd < 0){perror("socket error!\n");return -1;}printf("socket ok!\n");//按照服务器的ip地址和端口号连接服务器servAddr.sin_family = PF_INET;servAddr.sin_port = htons(10086);servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");ret = connect(sockFd, (struct sockaddr *)&servAddr, sizeof(servAddr));if(ret < 0){perror("connect error!");close(sockFd);return -1;}printf("connect ok!\n");//发送消息ret = send(sockFd, buf, sizeof(buf), 0);if(ret < 0){perror("send error!");close(sockFd);return -1;}printf("send ok!\n");//关闭套接字sleep(10);close(sockFd);return 0;
}
如果服务器突然停止,在重新启用,会出现下面的情况
在创建完socket套接字设置如下属性可以解决该情况
int nOptval;if (setsockopt(listenFd, SOL_SOCKET, SO_REUSEADDR,(const void *)&nOptval , sizeof(int)) < 0)//可以运行多个实例,一起接收广播信息{perror("setsocket error\n");return -1;}