socket实现简单客户端服务端通讯
2018-08-16 本文已影响38人
黑夜no烟丝
这是我自己写的客户端和服务端通信的Demo,没什么什么价值,旨在熟悉socket编程,为将来开发服务器打下基础,目前只能实现简单通讯,后面会陆续加上多线程,异步通讯,数据传输加密等功能,让我们一起进步吧。
服务端代码:
#Server.c:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char * argv[]) {
// insert code here...
int sfd,ind;
int ret;
socklen_t len;
struct sockaddr_in server;
struct sockaddr_in client;
char rcv[1024];
server.sin_family = AF_INET;
server.sin_port = htons(8000);
server.sin_addr.s_addr = htonl(INADDR_ANY);
sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0)
{
printf("socket 连接失败! sfd = %d ",sfd);
return -1;
}
ret = bind(sfd, (struct sockaddr *)&server, sizeof(struct sockaddr));
if (ret < 0 )
{
printf("绑定失败! ret = %d \n",ret);
return ret;
}
ret = listen(sfd, 10);
if (ret == -1)
{
printf("监听失败!");
return -1;
}
printf("============等待客户端发送请求!============\n");
while (1)
{
memset(&client,0x00,sizeof(client));
len = sizeof(client);
ind = accept(sfd, (struct sockaddr *)&client, &len);
if (ind < 0)
{
printf("接受客户端消息失败!ret = %d \r\n",ret);
return -1;
}
else
{
while (1)
{
memset(rcv, 0x00, sizeof(rcv));//这里一定要每次进来都初始化
//send(ind, "你好你好你好", 20, 0);//要发送给客户端消息可打开
recv(ind, rcv, sizeof(rcv), 0);
printf("rcv = %s \n",rcv);
}
}
}
return 0;
}
客户端代码:
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
#define BUFFER_SIZE 1024
int main(int argc, const char * argv[])
{
//我是在MAC终端下编写的,这里使用命令行参数传的服务端IP,如果不用这个形式,写死也可以
if(argc != 2)
{
printf("Usage: ./%s serverIP \n",argv[0]);
return -1;
}
struct sockaddr_in client;
bzero(&client,sizeof(client));
client.sin_family = AF_INET;
client.sin_addr.s_addr = htons(INADDR_ANY);
client.sin_port = htons(0);
int client_socket =socket(AF_INET,SOCK_STREAM,0);
if(client_socket < 0)
{
printf("创建scoket失败!\n");
return -1;
}
if(bind(client_socket,(struct sockaddr *)&client,sizeof(client)))
{
printf("绑定socket失败!\n");
return -1;
}
//配置服务端的信息
struct sockaddr_in server;
memset(&server,0x00,sizeof(server));
server.sin_family = AF_INET;
if(inet_aton(argv[1],&server.sin_addr) == 0)
{
printf("解析服务端IP失败 serverIP = %s\n",argv[1]);
return -1;
}
server.sin_port = htons(8000);//这里,服务端的端口号一定要配一个固定的,客户端可以随机分配,不影响
socklen_t server_len = sizeof(server);
//连接服务器
if(connect(client_socket,(struct sockaddr*)&server,server_len) < 0)
{
printf("连接服务端失败!\n");
return -1;
}
printf("=========连接服务端成功======\n");
while(1)
{
char sendline[BUFFER_SIZE];
memset(sendline,0x00,sizeof(sendline));
fgets(sendline,BUFFER_SIZE,stdin);
if(send(client_socket,sendline,strlen(sendline),0)<0)
{
printf("发送消息失败:%s(errno:%d)\n",strerror(errno),errno);
exit(0);
}
}
}
代码已经很简单了,感觉也没什么可说的了,后续加了功能再聊吧。
结果展示:
image.png