查看记录:10/20
今天又重新看了一下程序,觉得ListenKeyboard这个函数写的很好。利用select监听键盘,成功的解决了
必须输入才会刷新消息的问题。这样等待15秒后也可刷新消息,效果很好
----------------------------------修正之后第二版-----------------------------------------
Record: 1.在第一版的基础上添加了登录以及注册的功能
登录与注册的功能依赖文件UserList实现。
默认的用户为admin, 密码为admin
2.添加了用select实现的自动刷新功能
当用户停留在输入选择界面超过15秒后,便会自动刷新
好处就是别人发送的信息用户可以在等待15秒后直接看到(利用select)
3.将部分功能迁移到了.h文件中,便于查看代码与修改
-------------------------------------------------------------------------------------------------
【具体代码】
【server.c】
/************************************
Version:2.0
Author:Shaw Song
Program: server.c
Content: 1.one server to offer many
clients communicate server
2.add the function of sign
3.add the function of login
Records: shaw song 10/08 morning
shaw song 10/09 afternoon
************************************/
#include "server.h"
#define MAX_FD_NUM 100
#define MyPort 8888
int main()
{
int MaxFd=0;
int ConnectAmount = 0;
int ListenFd;
int ClientFd;
char Name[20];
struct timeval tv;
struct sockaddr_in ServerAddr, ClientAddr;
fd_set FdSet;
FdName fd_name_table[MAX_FD_NUM];
//create ListenFd
ListenFd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == ListenFd)
{
perror("socket create error :");
exit(1);
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(MyPort);
ServerAddr.sin_addr.s_addr = INADDR_ANY;
if (bind(ListenFd, (struct sockaddr *)&ServerAddr, sizeof(ServerAddr)) == -1)
{
perror("bind error:");
exit(1);
}
if (listen(ListenFd, 10) == -1)
{
perror("listen error");
exit(1);
}
//recv and send message
//init
MaxFd = ListenFd;
int i;
for (i = 0; i < MAX_FD_NUM; i++)
{
fd_name_table[i].fd = 0;
memset(fd_name_table[i].name, '\0', 20);
}
while(1)
{
FILE* file;
file = fopen("ChatRecord", "a+");
if (file < 0)
{
perror("open CharRecord fail!");
exit(1);
}
fseek(file, 0, SEEK_END);
//select
FD_ZERO(&FdSet);
FD_SET(ListenFd, &FdSet);
printf("--------------------------\n");
printf("now online %d clients:\n",ConnectAmount);
for(i = 0; i < MAX_FD_NUM; i++)
{
if(fd_name_table[i].fd != 0)
{
printf("%s\n",fd_name_table[i].name);
FD_SET(fd_name_table[i].fd, &FdSet);
if (fd_name_table[i].fd > MaxFd)
{
MaxFd = fd_name_table[i].fd;
}
}
}
tv.tv_sec = 10;
tv.tv_usec = 0;
int ret;
ret=select(MaxFd+1, &FdSet, NULL, NULL, &tv);
if (ret < 0)
{
perror("select error");
exit (1);
}
if (ret == 0)
{
// printf("time out!\n");
continue;
}
//connect to new client
if(FD_ISSET(ListenFd, &FdSet))
{
int sin_size=sizeof(ServerAddr);
memset(Name, '\0', 20);
ClientFd = accept(ListenFd, (struct sockaddr *)&ClientAddr, &sin_size);
printf("ClientFd:%d\n",ClientFd);
if (ClientFd < 0)
{
printf("can't accept a new ClientFd!\n");
continue;
}
if (Server_Login(ClientFd, Name) == 0)
close(ClientFd);
else
{
for (i = 0; i < MAX_FD_NUM; i++)
{
if(fd_name_table[i].fd == 0)
{
fd_name_table[i].fd = ClientFd;
memcpy(fd_name_table[i].name, Name,20);
break;
}
}
ConnectAmount++;
}
}
//recv and send
for (i = 0; i < MAX_FD_NUM; i++)
{
if (FD_ISSET(fd_name_table[i].fd, &FdSet))
{
char buffer[140];
memset(buffer, '\0', 140);
int recv_ret;
recv_ret = recv(fd_name_table[i].fd, buffer, sizeof(buffer), 0);
if (recv_ret <= 0)
{
printf("%s offline\n",fd_name_table[i].name);
close(fd_name_table[i].fd);
fd_name_table[i].fd = 0;
memset(fd_name_table[i].name, '\0',20);
ConnectAmount--;
FD_CLR(fd_name_table[i].fd, &FdSet);
break;
}
//fputs(buffer,file);
//fputs("\n",file);
char SendName[20];
char DestName[20];
char SendMsg[100];
memset(SendName,'\0',20);
memset(DestName,'\0',20);
memset(SendMsg,'\0',100);
split_string(buffer, DestName, SendName, SendMsg);
printf("%s %s %s\n",DestName,SendName, SendMsg);
int flag = 0;
int j = 0;
for (j = 0;j < MAX_FD_NUM; j++)
{
if (memcmp(DestName,fd_name_table[j].name,20) == 0)
{
int DestTemp = fd_name_table[j].fd;
send(DestTemp, buffer, sizeof(buffer),0);
fputs(buffer,file);
fputs("\n",file);
flag=1;
break;
}
else if (memcmp(DestName, "SIGN", 4) == 0)
{
Server_Sign(SendName, SendMsg);
flag = 1;
break;
}
}
if (!flag)
{
printf("can't find the %s!\n",DestName);
}
else
{
printf("send to the %s success!\n",DestName);
}
}
}
fclose(file);
}
}
【server.h】
/************************************
Version:2.0
Author:Shaw Song
Program: server.h
Content: 1.one server to offer many
clients communicate server
2.add the function of sign
3.add the function of login
Records: shaw song 10/08 morning
shaw song 10/09 afternoon
************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <arpa/inet.h>
#define USERFILE "UserList"
/**************************
Name:FdName
Function: relate the fd and
Client name
***************************/
typedef struct
{
int fd;
char name[20];
} FdName;
/********************************
Function Name:split_string
Function:split the string buffer
buffer:xxxxx#xxxx#xxxxx@
Parameter: char* p is the buffer
char* Dest Send Msg is
the DestName SenderName
and the Message Sended
*********************************/
void split_string(char* p, char* Dest, char *Send, char* Msg)
{
while(*p != '#')
*Dest++ = *p++;
p++;
while(*p != '#')
*Send++ = *p++;
p++;
while(*p != '@')
*Msg++ = *p++;
}
/********************************
Function Name:Server_Login
Function:confirm the UserName and
Passwd
Parameter: ClientFd is the fd of
the new Client
username is the name of
user
Return: type:int
1 means Login Success
0 means Login Fail
*********************************/
int Server_Login(int ClientFd, char* username)
{
int ret;
char RecvBuf[50];
memset(RecvBuf, '\0', 50);
ret = recv(ClientFd, RecvBuf, 50, 0);
if (ret <= 0)
{
printf("Recv UserName and PassWord Fail!\n");
return 0;
}
//init Name
char* p = NULL;
p = RecvBuf;
while(*p != '#')
*username++ = *p++;
//confirm
FILE* LoginFile;
LoginFile = fopen (USERFILE, "a+");
if (fgetc(LoginFile) == EOF)
{
char *buff="admin#admin@";
fputs(buff, LoginFile);
}
fseek(LoginFile, 0, SEEK_SET);
char temp[50];
while (fscanf(LoginFile, "%s@", temp) != EOF)
{
strcat(temp,"\0");
//printf("%s\n",temp);
//printf("%s\n",RecvBuf);
if (strcmp (temp, RecvBuf) == 0)
{
printf("Log in success!\n");
send(ClientFd, "LOGI", 5, 0);
fclose(LoginFile);
return 1 ;
}
}
send(ClientFd, "FAIL", 5, 0);
fclose(LoginFile);
return 0;
}
/***********************************************
Function Name: Server_Sign
Function: sign a new user in the Userlist
Parameter:UserName, Password
************************************************/
void Server_Sign(char* username, char* passwd)
{
FILE* SignFile;
SignFile = fopen(USERFILE, "a+");
fseek(SignFile, 0, SEEK_END);
fputs("\n", SignFile);
fputs(username, SignFile);
fputs("#",SignFile);
fputs(passwd, SignFile);
fputs("@",SignFile);
fclose(SignFile);
}
【client.c】
/***********************************
Version:2.0
Program: client.c
Content: 1.one server to offer many
clients communicate server.
2.add the function of sign
and login.
Records: shaw song 10/08 afternoon
shaw song 10/10 morning
***********************************/
#include "client.h"
#define MyPort 8888
int main(int argc, char ** argv)
{
//init var
int ClientFd;
struct sockaddr_in ClientAddr;
char MyName[20];
memset(MyName, '\0', 20);
char buffer[140];
memset(buffer, '\0',140);
char DestName[20];
memset(DestName,'\0',20);
char SendName[20];
memset(SendName,'\0',20);
char SendMsg[100];
memset(SendName,'\0',100);
//input client name
//printf("Please input the Client Name\n");
//scanf("%s", MyName);
ClientFd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == ClientFd)
{
perror("Socket Create fail");
exit(1);
}
//connect
ClientAddr.sin_family = AF_INET;
ClientAddr.sin_port = htons(MyPort);
ClientAddr.sin_addr.s_addr = inet_addr(argv[1]);
memset(ClientAddr.sin_zero, 0, 8);
if (connect(ClientFd, (struct sockaddr*)&ClientAddr, sizeof(ClientAddr)) < 0)
{
perror("connect error");
return 0;
}
printf("connect success!\n");
//Client Login
if (Client_Login(ClientFd, MyName) == 0)
{
close(ClientFd);
printf("Press any key to exit\n");
char t ;
scanf("%c",&t);
exit(0);
}
while(1)
{
//confirm if a message can receive
fd_set FdSet;
FD_ZERO(&FdSet);
FD_SET(ClientFd, &FdSet);
int ret;
struct timeval tv;
tv.tv_sec=1;
tv.tv_usec=0;
printf("\n-------%s Message Receive------\n", MyName);
while (1)
{
int tmp = select(ClientFd+1, &FdSet, NULL, NULL, &tv);
if(!FD_ISSET(ClientFd, &FdSet) || tmp == 0)
{
break;
}
ret = recv(ClientFd, buffer, sizeof(buffer), 0);
if (ret <= 0)
{
perror("recover fail");
close(ClientFd);
exit(1);
}
split_string(buffer,DestName,SendName,SendMsg);
printf(" %s:%s\n", SendName, SendMsg);
}
printf("-------------END---------------\n\n");
/* function */
int chs;
printf(">>>>Please choose the number<<<<\n");
printf("1.Sign a new user\n");
printf("2.Talk to other Client\n");
printf("3.Quit and exit\n");
printf(">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<\n");
//scanf("%d",&chs);
chs = ListenKeyboard();
if (chs == 0)
continue;
if (chs == 1)
Client_Sign(ClientFd);
else if (chs == 2)
Client_Talk(ClientFd, MyName);
else if (chs == 3)
{
printf("Client Quit!\n");
close(ClientFd);
return 0;
}
}
}
【client.h】
/***********************************
Version:2.0
Program: client.h
Content: 1.one server to offer many
clients communicate server.
2.add the function of sign
and login.
Records: shaw song 10/08 afternoon
shaw song 10/10 morning
***********************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <arpa/inet.h>
/********************************
Function Name:split_string
Function:split the string buffer
buffer:xxxxx#xxxx#xxxxx@
Parameter: char* p is the buffer
char* Dest Send Msg is
the DestName SenderName
and the Message Sended
*********************************/
void split_string(char* p, char* Dest, char* Send, char* Msg)
{
while(*p != '#')
*Dest++ = *p++;
p++;
while(*p != '#')
*Send++ = *p++;
p++;
while(*p != '@')
*Msg++ = *p++;
}
/*********************************
Function Name:Client_Login
Function:Send the UserName and Passwd
to Login
Parameter: ClientFd is the fd of Client
Return: type:int
1 means Login Success
0 means Login Fail
***********************************/
int Client_Login(int ClientFd, char *myname)
{
char UserName[20];
char Passwd[20];
memset(UserName, '\0', 20);
memset(Passwd, '\0', 20);
printf("Please input your name : ");
scanf("%s", UserName);
memcpy(myname, UserName, 20);
printf("Please input your password : ");
scanf("%s", Passwd);
//Send
char SendBuf[50];
memcpy(SendBuf, UserName, 20);
strcat(SendBuf,"#");
strcat(SendBuf, Passwd);
strcat(SendBuf, "@");
send(ClientFd, SendBuf, 50, 0);
//recv
char ans[5];
int ret;
ret = recv(ClientFd, ans, 5, 0);
if (ret <= 0)
return 0;
if (memcmp(ans, "LOGI", 4) == 0)
{
printf("Login in Success!\n");
return 1;
}
else
{
printf("Login Fail!!\nWrong username or passwd\n");
return 0;
}
}
/****************************************
Function Name: Client_Sign
Function:sign a new user
Parameter: ClientFd
*****************************************/
void Client_Sign(int ClientFd)
{
char UserName[20];
char PassWord[20];
char SendBuf[50];
memset(UserName, '\0', 20);
memset(PassWord, '\0', 20);
memset(SendBuf, '\0', 50);
printf("*****Sign a new user*****\n");
printf("Please input new Username: ");
scanf("%s", UserName);
printf("Please input the password: ");
scanf("%s", PassWord);
printf("**************************\n");
memcpy(SendBuf, "SIGN#", 6);
strcat(SendBuf, UserName);
strcat(SendBuf, "#");
strcat(SendBuf, PassWord);
strcat(SendBuf, "@");
send(ClientFd, SendBuf, 50, 0);
}
/****************************************
Function Name: Client_Talk
Function:talk to other Client
Parameter: ClientFd
*****************************************/
void Client_Talk(int ClientFd, char *MyName)
{
char SendName[20];
char DestName[20];
char SendMsg[100];
char buffer[140];
memset(SendName, '\0', 20);
memset(DestName, '\0', 20);
memset(SendMsg, '\0', 100);
memset(buffer, '\0', 140); char ans='y';
printf("Send Message\n");
if(ans == 'y')
{
printf("Please input the Dest Client Name:");
scanf("%s", DestName);
printf("Please input the Message:");
scanf("%s", SendMsg);
strcpy(buffer,DestName);
strcat(buffer, "#");
strcat(buffer,MyName);
strcat(buffer, "#");
strcat(buffer,SendMsg);
strcat(buffer, "@");
int ret = send(ClientFd, buffer, sizeof(buffer), 0);
if (ret > 0)
{
printf("Message is sended!\n");
}
else
printf("fail to send message!\n");
}
}
/*****************************************
Function Name:ListenKeyboard
Function:listen teh keyboard ,if there is a
input then return
*****************************************/
int ListenKeyboard()
{
fd_set key;
FD_ZERO(&key);
FD_SET(0, &key);
int KeyRet;
int buf;
struct timeval KeyTv;
KeyTv.tv_sec =15;
KeyTv.tv_usec = 0;
KeyRet = select(1, &key, NULL, NULL, &KeyTv);
if(KeyRet == 0)
{
system("clear");
return 0;
}
else if(KeyRet > 0);
{
scanf("%d",&buf);
return buf;
}
printf("wrong input!\n");
}
- IPC进程之间通信的几种方式
概念 进程间通信就是在不同进程之间传播或交换信息,那么不同进程之间存在着什么双方都可以访问的介质呢?进程的用户空间是互相独立的,一般而言是不能互相访问的,唯一的例外是 共享内存区 .但是,系统空间却是 ...
- Python进阶----进程之间通信(互斥锁,队列(参数:timeout和block),), ***生产消费者模型
Python进阶----进程之间通信(互斥锁,队列(参数:timeout和block),), ***生产消费者模型 一丶互斥锁 含义: 每个对象都对应于一个可称为" 互斥锁&qu ...
- 【转】wpa_supplicant与wpa_cli之间通信过程
[转]wpa_supplicant与wpa_cli之间通信过程 转自:http://blog.chinaunix.net/uid-26585427-id-4051479.html wpa_suppli ...
- 【linux】mkfifo 命令创建命名管道实现进程之间通信
mkfifo 命令 mkfifo命令创建一个FIFO特殊文件,是一个命名管道(可以用来做进程之间通信的桥梁) 管道也是一种文件,一般是linux中的一个页大小,4k,管道数据一旦被读取就没了.(管道大 ...
- 客户端与服务器之间通信收不到信息——readLine()
写服务器端和客户端之间通信,结果一直读取不到信息,在https://blog.csdn.net/yiluxiangqian7715/article/details/50173573 上找到了原因:使用 ...
- 【Vue课堂】Vue.js 父子组件之间通信的十种方式
这篇文章介绍了Vue.js 父子组件之间通信的十种方式,不管是初学者还是已经在用 Vue 的开发者都会有所收获.无可否认,现在无论大厂还是小厂都已经用上了 Vue.js 框架,简单易上手不说,教程详尽 ...
- VLAN之间通信-三层交换
实验目的 VLAN之间通信-三层交换 掌握配置VLANIF接口的方法 理解数据包跨VLAN路由的原理 掌握测试多层交换网络连通性的方法 实验原理 三层交换机在原有二层交换机的基础之上增加了路由功能,同 ...
- 【原创】Docker实战 Dockerfile最佳实践&&容器之间通信
官方最佳实践文档 https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#from Docker实战(三十) ...
- iframe之间通信问题及iframe自适应高度问题
下面本人来谈谈iframe之间通信问题及iframe自适应高度问题. 1. iframe通信 分为:同域通信 和 跨域通信.所谓同域通信是指 http://localhost/demo/iframe/ ...
随机推荐
- AE + GDAL实现影像按标准图幅分割(上)
最近有个项目,其中有个功能是要将遥感影像按标准图幅分割,一开始用AE的接口,慢的让人抓狂,就改用GDAL,速度提升很大.我主要通过http://blog.csdn.net/liminlu0314/学习 ...
- keystone无法查看catalog并且用户无法申请令牌的解决方案
在运行openstack catalog list之后提示: Only an authorized user may issue a new token. #只有授权用户才能申请token opens ...
- 一键部署ETCD集群脚本
这里使用三个节点,系统版本为CentOS7 # vim deploy-etcd.sh #!/bin/bash set -x set -e #更改这里的IP, 只支持部署3个节点etcd集群 decla ...
- SSH整合(一)hibernate+spring
1.导入maven节点 <dependencies> //测试用的 <dependency> <groupId>junit</groupId> < ...
- Invalid command 'RailsBaseURI'
官方指导 http://www.redmine.org/projects/redmine/wiki/HowTo_Install_Redmine_on_Ubuntu_step_by_step 解决使 ...
- delphi 7 mdi子窗体。。。无法更改以命令对象为源的记录集对象的 ActiveConnection 属性。
问题是这样的 我做了一个小程序 把 adoconnection放到了主窗体 连接的是access数据库; 新建了一个子窗体继承自FBase 新建了一个pubulic方法 qrySearch 实现了 ...
- AngularJS学习笔记5
11.AngularJS HTML DOM ng-disabled 指令直接绑定应用程序数据到 HTML 的 disabled 属性. <button ng-disabled="my ...
- webapp 1px显示两倍的问题
公司最近换新首页,按照设计师的要求<大家都在逛>的分割线要1个像素. .span-3{ width:33.3333%; &:not(:first-child){ &:bef ...
- HTML和CSS的知识点
HTML的知识点 HTML的结构: <!DOCTYPE html>: 文档类型性为HTML5文件 文档声明:在HTML的文档中必不可少,且必须在文档的第一行 文档声明的编码格式<!- ...
- 简单的后台数据和前台数据交互.net
最近忙着做POS项目,心血来来潮写了点小项目. 更具要求是随机显示数据并且产生的数据是可以控制的.前台交互显示能够倒叙,切每次只显示一条,页面不能超过20条超过的部分做删除. 我先展示一下前台的代码, ...