要实现客户端与服务器端的通讯,需要两部分C++的程序:服务器端程序代码和客户端代码。
首先是服务器端程序代码:
#include <WinSock2.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib, "ws2_32.lib")
void main()
{
WSADATA wsaData
int port = 5099
char buf[] = "Server: hello, I am a server....."
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("Failed to load Winsock")
return
}
//创建用于监听的套接字
SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0)
SOCKADDR_IN addrSrv
addrSrv.sin_family = AF_INET
addrSrv.sin_port = htons(port)//1024以上的端口号
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY)
int retVal = bind(sockSrv, (LPSOCKADDR)&addrSrv, sizeof(SOCKADDR_IN))
if(retVal == SOCKET_ERROR){
printf("Failed bind:%d\n", WSAGetLastError())
return
}
if(listen(sockSrv,10) ==SOCKET_ERROR){
printf("Listen failed:%d", WSAGetLastError())
return
}
SOCKADDR_IN addrClient
int len = sizeof(SOCKADDR)
while(1)
{
//等待客户请求到来
SOCKET sockConn = accept(sockSrv, (SOCKADDR *) &addrClient, &len)
if(sockConn == SOCKET_ERROR){
printf("Accept failed:%d", WSAGetLastError())
break
}
printf("Accept client IP:[%s]\n", inet_ntoa(addrClient.sin_addr))
//发送数据
int iSend = send(sockConn, buf, sizeof(buf) , 0)
if(iSend == SOCKET_ERROR){
printf("send failed")
break
}
char recvBuf[100]
memset(recvBuf, 0, sizeof(recvBuf))
// //接收数据
recv(sockConn, recvBuf, sizeof(recvBuf), 0)
printf("%s\n", recvBuf)
closesocket(sockConn)
}
closesocket(sockSrv)
WSACleanup()
system("pause")
}
接下来是客户端代码:
#include <WinSock2.h>#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
void main()
{
//加载套接字
WSADATA wsaData
char buff[1024]
memset(buff, 0, sizeof(buff))
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("Failed to load Winsock")
return
}
SOCKADDR_IN addrSrv
addrSrv.sin_family = AF_INET
addrSrv.sin_port = htons(5099)
addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1")
//创建套接字
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0)
if(SOCKET_ERROR == sockClient){
printf("Socket() error:%d", WSAGetLastError())
return
}
//向服务器发出连接请求
if(connect(sockClient, (struct sockaddr*)&addrSrv, sizeof(addrSrv)) == INVALID_SOCKET){
printf("Connect failed:%d", WSAGetLastError())
return
}else
{
//接收数据
recv(sockClient, buff, sizeof(buff), 0)
printf("%s\n", buff)
}
//发送数据
char buff = "hello, this is a Client...."
send(sockClient, buff, sizeof(buff), 0)
//关闭套接字
closesocket(sockClient)
WSACleanup()
}
分析:跟据楼主的意思!我们可以得出,这个程序只要求我们写查询通迅录的内容
而通迅录的内容,可以通过初始化得出!
简而言之:写一个查询函数
呵呵···把问题相通了,我们就开始写算法吧let's go!!!
----------------------------------------------------------------
算法:
1.获得用户的输入 (就是要查询的对象的名字)
2.查询 (在这我用穷举通迅录的方式查询了,^_^&&^_^)
3.输出查询结果
算法就这样被我们征服了!!!呵呵~~好有成就感哇!!
但我们现在还不能开始编码,我得们先想好怎么编,要做到胸有成竹!!!
那我现在来想一下该怎么编码吧!let's go!!!
----------------------------------------------------------------
要保存通迅的信息,那么我们得用一个结构体吧:
struct friends
{
char name[20]/* 名字不能写得太长哦 */
char province[20]/* 省份 */
char city[20]/* 所在城市 */
char nation[20]/* 民族 */
char sex[2]/* 性别 M/F */
int age/* 年龄 */
}
要获得用户输入,要用个 char search_name[20]
查询结果反回一个数,记录对象在通迅录中的位置:int index
查询中有用要循环,用一个记数器: int i
----------------------------------------------------------------
OK,该用的变量我们都想好了!算法我们也想好了。还等什么呢,开始编码吧
呵呵~~是不是等这个时候都等得急了~~~~~
-------------------------------------------------------------------
*******************************************************************
******* 程序实现:
*******************************************************************
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* 定义保存通迅录的信息 */
struct friends
{
char name[20]/* 名字 */
char province[20]/* 省份 */
char city[20]/* 所在城市 */
char nation[20]/* 民族 */
char sex[2]/* 性别 M/F */
int age/* 年龄 */
}
void getname (char search_name[])
int search (struct friends friend_list[], char search_name[])
void print_result(struct friends friend_list[], int index)
int main (void)
{
int index
char search_name[20]
struct friends friend_list[4] = {
{"lihan", "liaoning", "huluodao","han","M",19},
{"zhuqiang", "jiangsu", "changzhu", "han","M",19},
{"wangjiangang", "liaoning", "anshan","han","M",20},
{"zhanghongwei", "shandong", "zhucheng", "han","M",21},
}
(void) getname (search_name)/* 获得用户输入 */
index = search (friend_list, search_name)/* 查询 */
(void) print_result (friend_list,index)/* 打印结果 */
return 0
}
/****************************************
*** 函数名:getname
*** 功能:获得用户要查询的对象的名字
****************************************/
void getname (char search_name[])
{
printf ("Pleace enter the name of your friends you want to search>>")
scanf ("%s", search_name)
}
/****************************************
*** 函数名:search
*** 功能:查询对象
****************************************/
int search (struct friends friend_list[], char search_name[])
{
int i
/* 穷举通迅录 */
for (i = 0i <4++i)
{
if (strcmp(friend_list[i].name, search_name) == 0)
{
return (i)
}
}
if (i == 4)
{
printf ("I am sorry! there is nobody by the name you enter!\n")
fflush(stdin)
getchar()
exit (0)
}
}
/****************************************
*** 函数名:print_result
*** 功能:打印结果
****************************************/
void print_result(struct friends friend_list[], int index)
{
printf ("the imformation of %s:\n", friend_list[index].name)
printf ("------------------------------------------------\n")
printf (" NAME: %-s\n", friend_list[index].name)
printf ("PROVINCE: %-s\n", friend_list[index].province)
printf (" CITY: %-s\n", friend_list[index].city)
printf (" NATION: %-s\n", friend_list[index].nation)
printf (" SEX: %-s\n", friend_list[index].sex)
printf (" AGE: %-d\n", friend_list[index].age)
printf ("-------------------------------------------------\n")
fflush(stdin)
getchar()
}
*****************************************************************************
*****************************************************************************
呵呵~~一口气把它写出来了!!!前期写算法是很重要的!!
现在还没结束!!我们要先来测试一下!!
--------------------------------------
Pleace enter the name of your friends you want to search>>lihan
the imformation of lihan:
------------------------------------------------
NAME: lihan
PROVINCE: liaoning
CITY: huluodao
NATION: han
SEX: M
AGE: 19
-------------------------------------------------
--------------------------------------
Pleace enter the name of your friends you want to search>>lbmzwyy
I am sorry! there is nobody by the name you enter!
说明成功了~~~呵呵~~太高兴了~~
--------------------------------------
请记注一点:克制编码的诱惑
无论多么小的问题都要先分析好问题,想好算法,才能开始编码!!!我相信这样做一定对你有好处的!
#include#include
#include
#include
#define maxlen 15
struct persons
{
int num
char name[20]
char e_addr[20]
char tel_no[15]
char sim_no
char arch
}persons[maxlen]
typedef struct lnode{
int num
char name[20]
char e_addr[20]
char tel_no[15]
char sim_no
char arch
struct lnode *next
}listnode,*linklist
linklist head=NULL,r=NULL
listnode *s,*p0,*p1,*p2,*p3,*p4,*p5,*p6,*p7,*p8,*p9
int i
char name1[10],chchar tel_no1[15]char arch1char sim_no1char e_addr1[20]
char s1[20]
FILE *fp
void creat()
{
int j
long k
fp=fopen("数据文件.txt","r t")
if(fp!=NULL)
{for(i=0i<=maxleni++ )
{ j=fgetc(fp)
if(j==EOF)
return
k=i
fseek(fp,k*sizeof(struct persons),0)
fread(&persons[i],sizeof(struct persons),1,fp)
s=(linklist)malloc(sizeof(listnode))
s->num=persons[i].num
strcpy(s->name,persons[i].name)
strcpy(s->e_addr,persons[i].e_addr)
strcpy(s->tel_no,persons[i].tel_no)
s->sim_no=persons[i].sim_no
s->arch=persons[i].arch
if(head==NULL)
{head=sr=headhead->next=NULL}
else
{r->next=s
r=sr->next=NULL
}}fclose(fp)}
else
{ fp=fopen("数据文件.txt","w")
i=1
}
}
void ShowA()
{p1=head
while(p1!=NULL)
{if(p1->arch=='A')
{
cout<<endl
cout<name<<endl
cout<tel_no<<endl
cout<sim_no<<endl}
p1=p1->nextcontinue}
}
void ShowB()
{p1=head
while(p1!=NULL)
{if(p1->arch=='B')
{
cout<<endl
cout<name<<endl
cout<tel_no<<endl
cout<sim_no<<endl}
p1=p1->nextcontinue}
}
void ShowC()
{p1=head
while(p1!=NULL)
{if(p1->arch=='C')
{
cout<<endl
cout<name<<endl
cout<tel_no<<endl
cout<sim_no<<endl}
p1=p1->nextcontinue}
}
void Show()
{char ch1
printf(" Which arch do you want to show?\n")
cout<<" A:同学同事"<<"B:家人"<<"C:其他"<<endl
cout<<"请选择:"<<endl
cin>>ch1
switch(ch1)
{case'A':ShowA()break
case'B':ShowB()break
case'C':ShowC()break
default:cout<<"error"<<endl
}
}
void Delete()
{ printf("\n\n\t 请输入要删除用户的姓名:")
cin>>name1
p4=head
if(strcmp(p4->name,name1)==0)
{ p4=p4->next
head=p4
}
else
{ while(strcmp(p4->next->name,name1)!=0)
p4=p4->next
p5=p4->next
p4->next=p5->next
free(p5)
}
}
void Input()
{ s=(linklist)malloc(sizeof(listnode))
printf("\n\n\t 请输入该用户的信息:")
cout<<"name:"
cin>>s->name
cout<<"tel_no:"
cin>>s->tel_no
cout<<"sim_no:"
cin>>s->sim_no
cout<<"e_addr:"
cin>>s->e_addr
cout<<"arch:"
cin>>s->arch
if(head==NULL)printf("\n\n")
else
{p8=head
while(p8!=NULL&&strcmp(s->name,p8->name)!=0&&strcmp(s->tel_no,p8->tel_no)!=0)
p8=p8->next
if(p8!=NULL)
{printf(" 您添加的用户已存在!")
free(s)}}
if(head==NULL)
{head=shead->next=NULL}
else
{r->next=s
r=sr->next=NULL}
}
void Alter()
{
printf("\n\n\t 请输入姓名:")
cin>>name1
p3=head
while(p3!=NULL&&strcmp(name1,p3->name)!=0)
p3=p3->next
if(p3==NULL)
printf("\n\n\t 您选择的用户不存在!")
else
{ printf("\n\n\t 请输入该用户的新信息!")
cout<<"name:"
cin>>name1
cout<<"tel_no:"
cin>>tel_no1
cout<<"e_addr:"
cin>>e_addr1
cout<<"sim_no:"
cin>>sim_no1
cout<<"arch:"
cin>>arch1
while(p9!=NULL&&strcmp(name1,p9->name)!=0&&strcmp(tel_no1,p9->tel_no)!=0)
p9=p9->next
if(p9==NULL)
{strcpy(p3->name,name1)
strcpy(p3->tel_no,tel_no1)
strcpy(p3->e_addr,e_addr1)
p3->sim_no=sim_no1
p3->arch=arch1
}
else
printf(" 您添加的用户已存在!")
}
}
void Dial()
{int achar b
cout<<"1.拨叫用户:"<<endl
cout<<"2.使用单键拨号:"<<endl
cin>>a
p0=head
if(a==1)
{cout<<" 请输入拨叫用户的姓名:"
cin>>name1
while(strcmp(name1,p0->name)!=0&&p0!=NULL)
p0=p0->next
if(p0==NULL)
cout<<" 您选择的用户不存在!"
else
/*for(c=0c<15c++)
{cout<<endl
cout<<(*p0).tel_no[c]}*/
{cout<<endl
cout<tel_no
cout<<endl}
}
else
{cout<<"请输入单键号码:"
cin>>b
while(p0!=NULL&&b!=p0->sim_no)
p0=p0->next
if(p0==NULL)
cout<<" 您输入的单键号码不存在!"
else
{cout<<endl
cout<name<<endl
cout<tel_no
cout<<endl}
}
}
void Save()
{ int j
fp=fopen("数据文件.txt","w")
for(p2=head,j=0p2!=NULLj++ ,p2=p2->next)
{
strcpy(persons[j].name,p2->name)
strcpy(persons[j].tel_no,p2->tel_no)
persons[j].sim_no=p2->sim_no
strcpy(persons[j].e_addr,p2->e_addr)
persons[j].arch=p2->arch
fwrite(&persons[j],sizeof(struct persons),1,fp)
}
}
void main()
{ creat()
do
{
printf(" **********************************************************")
printf("\n\n\n\n\t 欢迎来到通讯录!")
printf("\n\n\t\t 请选择 *** 作:")
printf("\n\t\t1. 显示通讯录")
printf("\n\t\t2. 删除通讯录")
printf("\n\t\t3. 添加通讯录")
printf("\n\t\t4. 编辑通讯录")
printf("\n\t\t5. 拨号功能")
printf("\n\t\t6. 保存刚才的 *** 作并退出\n")
printf(" **********************************************************")
printf("\n\n\n")
printf("\t 选择您想要的 *** 作:")
cin>>ch
switch(ch)
{ case '1': Show()
break
case '2': Delete()
break
case '3': Input()
break
case '4': Alter()
break
case '5': Dial()
break
case '6': Save()
fclose(fp)
exit(0)
break
default:
printf("\n\t*********************************\n")
printf("\n\t The num should 1-6!!! \n")
printf("\n\t**********************************")
break
}
}while(1)
}
转的.......woyuyuchao
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)