先看下效果 :
启动服务器端 :
启动客户端:
客户端向服务器端发送:i am client
服务器端收到 并回送 i am server
一直 循环 直到客户端发送 quit 退出系统
客户端发送quit的时候 服务器端也会退出
作为最基础的socket入门练习
服务器端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#define PORT 6666
#define BACKLOG 10
#define MAX_SIZE 2048
int main()
{
int socket_fd;
struct sockaddr_in server_addr;
char buffer[MAX_SIZE]={0};
char message[MAX_SIZE];
socket_fd = socket(AF_INET,SOCK_STREAM,0);
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port=htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
bind(socket_fd,(struct sockaddr *)&server_addr,sizeof(server_addr));
listen(socket_fd,BACKLOG);
printf("Server bind success \n");
struct sockaddr_in peer_addr;
socklen_t peer_len = sizeof(peer_addr);
while(1)
{
int client_fd;
client_fd = accept(socket_fd,(struct sockaddr* )&peer_addr,&peer_len);
printf("Receive a connect from clinet fd[%d,ip:%s,port:%d]\n",
client_fd,inet_ntoa(peer_addr.sin_addr),ntohs(peer_addr.sin_port));
while (1)
{
memset(buffer,0,sizeof(buffer));
int recv_len = recv(client_fd,buffer,MAX_SIZE,0);
if(recv_len == 0)
{
printf("Clinet is already closed\n");
break;
}
else
{
printf("Recv len is %d \n",recv_len);
}
printf("Clinet says:\n");
strcpy(message,buffer);
fputs(message,stdout);
memset(buffer,0,MAX_SIZE);
printf("Please input:\n");
fgets(buffer,sizeof(buffer),stdin);
send(client_fd,buffer,recv_len,0);
}
close(client_fd);
break;
}
close(socket_fd);
printf("Server exit\n");
return 0;
}
客户端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#define CLIETN_PORT 6666
#define MAX_SIZE 2048
int main(int argc,char *argv[])
{
if(argc != 2)
{
printf("Please input server ip\n");
exit(1);
}
char buffer[MAX_SIZE];
int socket_fd = socket(AF_INET,SOCK_STREAM,0);
const char *server_ip = argv[1];
struct sockaddr_in server_addr;
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(CLIETN_PORT);
inet_pton(AF_INET,server_ip,&server_addr.sin_addr);
connect(socket_fd,(struct sockaddr*)&server_addr,sizeof(server_addr));
printf("Connect to server success\n");
memset(buffer,0,MAX_SIZE);
printf("Please input:\n");
while (fgets(buffer,sizeof(buffer),stdin) != NULL)
{
if(strncmp(buffer,"quit",4) == 0)
{
printf("intpu is: quit break\n");
break;
}
else
{
printf("intpu is: %s\n",buffer);
}
send(socket_fd,buffer,strlen(buffer),0);
memset(buffer,0,sizeof(buffer));
recv(socket_fd,buffer,sizeof(buffer),0);
printf("Server says:\n");
fputs(buffer,stdout);
memset(buffer,0,sizeof(buffer));
printf("Please input:\n");
}
printf("Client will be closed\n");
close(socket_fd);
return 0;
}