因近期准备找工作,就翻出笔记看了下,整理出来大家看下指正下(ps:为什么发帖时没有C/C++的选项)
[C] 纯文本查看 复制代码 //服务端代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> //INADDR_ANY
#include <string.h>
int main(int argc , char *argv[])
{
if (argc < 2) //端口参数,发现停止运行后,服务端端口一直没释放,猜测是非正常退出导致没关闭服务
{
return -1;
}
int ss = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_sockaddr;
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_port = htons(atoi(argv[1]));
server_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(ss, (struct sockaddr *) &server_sockaddr, sizeof(server_sockaddr) ) == -1 )
{
printf("bind error\n");
return -1;
}
if (listen(ss, 5) == -1)
{
printf("listen error\n");
return -1;
}
char buff[1024] = {};
struct sockaddr_in client_addr;
socklen_t length = sizeof(client_addr);
int sc = accept(ss, (struct sockaddr*)&client_addr, &length);
if (sc < 0 )
{
printf("sc error\n");
return -1;
}
while(1)
{
memset(buff, 0, sizeof(buff));
int len = recv(sc, buff, sizeof(buff), 0);
printf("recv: %s\n",buff );
send(sc, buff, sizeof(buff), 0);
}
close(sc);
close(ss);
return 0;
}
[C] 纯文本查看 复制代码 //客户端代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> //INADDR_ANY
#include <string.h>
int main(int argc, char* argv[])
{
if (argc < 2) //端口参数,发现停止运行后,服务端端口一直没释放,猜测是非正常退出导致没关闭服务
{
return -1;
}
int sc = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(atoi(argv[1])); //服务器端口
serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //服务器ip
if(connect(sc, (struct sockaddr *)&serveraddr , sizeof(serveraddr)) < 0)
{
printf("conn error\n");
return 0;
}
char sendbuff[1024];
char recvbuff[1024];
while(1)
{
fgets(sendbuff, sizeof(sendbuff), stdin);
send(sc, sendbuff, strlen(sendbuff), 0);
recv(sc, recvbuff, sizeof(recvbuff), 0);
printf("recv: %s\n", recvbuff);
memset(recvbuff, 0, sizeof(recvbuff));
memset(sendbuff, 0 , sizeof(sendbuff));
}
close(sc);
return 0;
} |