关闭

MFC Socket简单服务器与客户端源码

335人阅读 评论(0) 收藏 举报

原博文:http://binge518.blog.51cto.com/1554719/1222251

以下是使用Socket写的简单服务器和客户端部分代码,主要是让初学者知道socket通信的原理,以及代码的编写方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include "stdafx.h"
#include "MTServer.h"
SOCKET server;
using namespace std;
UINT  MTServerThread(LPVOID pParam);
UINT  ClientThread(LPVOID pParam);
BOOL ParseCmd(char *str, CString& cmd, CString& params);
BOOL SendFile(SOCKET s, CString fname);
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0; 
    cout << "Press ESCAPE to terminate program\r\n";
    AfxBeginThread(MTServerThread,0);
    while(_getch()!=27);
    closesocket(server);
    WSACleanup();
    return nRetCode;
}
UINT  MTServerThread(LPVOID pParam)
{     
    WSADATA wsaData;
    sockaddr_in local;
    int wsaret=WSAStartup(0x101,&wsaData);
    if(wsaret!=0)
    {
        return 0;
    }
    local.sin_family=AF_INET;
    local.sin_addr.s_addr=INADDR_ANY;
    local.sin_port=htons((u_short)20248);
    server=socket(AF_INET,SOCK_STREAM,0);
    if(server==INVALID_SOCKET)
    {
        return 0;
    }
    if(bind(server,(sockaddr*)&local,sizeof(local))!=0)
    {
        return 0;
    }
    if(listen(server,10)!=0)
    {
        return 0;
    }
    SOCKET client;
    sockaddr_in from;
    int fromlen=sizeof(from);
    while(true)
    {
        client=accept(server,
            (struct sockaddr*)&from,&fromlen);
        AfxBeginThread(ClientThread,(LPVOID)client);  
    
    return 0;
}
UINT  ClientThread(LPVOID pParam)
{
    char buff[512];
    CString cmd;
    CString params;
    int n;
    int x;
    BOOL auth=false;
    SOCKET client=(SOCKET)pParam;
    strcpy(buff,"#Server Ready.\r\n");
    send(client,buff,strlen(buff),0);
    while(true)
    {
        n=recv(client,buff,512,0);
        if(n==SOCKET_ERROR )          
            break;
        buff[n]=0;
        if(ParseCmd(buff,cmd,params))
        {
            if(cmd=="QUIT")
                break;
            if(cmd=="AUTH")
            {
                if(params=="passwd")
                {
                    auth=true;
                    strcpy(buff,"#You are logged in.\r\n");
                }
                else
                {
                    strcpy(buff,"!Bad password.\r\n");
                }
                send(client,buff,strlen(buff),0);
            }
            if(cmd=="FILE")
            {
                if(auth)
                {
                    if(SendFile(client,params))
                        sprintf(buff,"#File %s sent successfully.\r\n",params);
                    else
                        sprintf(buff,"!File %s could not be opened.\r\n",params);
                    x=send(client,buff,strlen(buff),0);               
                }
                else
                {
                    strcpy(buff,"!You are not logged in.\r\n");
                    send(client,buff,strlen(buff),0);
                }
            }
        }
        else
        {
            strcpy(buff,"!Invalid command.\r\n");
            send(client,buff,strlen(buff),0);
        }
    }     
    closesocket(client);
    return 0;
}
BOOL ParseCmd(char *str, CString& cmd, CString& params)
{
    int n;
    CString tmp=str;  
    tmp.TrimLeft();
    tmp.TrimRight();  
    if((n=tmp.Find(' '))==-1)
    {
        tmp.MakeUpper();
        if(tmp!="QUIT")
            return false;
        cmd=tmp;
        return true;
    }     
    cmd=tmp.Left(n);
    params=tmp.Mid(n+1);
    cmd.MakeUpper();
    if((cmd!="AUTH") && (cmd!="FILE"))
        return false;
    return true;
}
BOOL SendFile(SOCKET s, CString fname)
    CFile f;
    BOOL p=f.Open(fname,CFile::modeRead); 
    char buff[1024];
    int y;
    int x;
    if(!p)
        return false;
    while(true)
    {     
        y=f.Read(buff,1024);
        x=send(s,buff,y,0);   
        if(y<1024)
        {
            f.Close();
            break;
        }         
    
    return true;
}


下面是客户端部分代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#include "stdafx.h"
#include "MTSClient.h"
int EndFile(char *buff, int len) ;
int NoFile(char *buff, int len) ;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    const char* servername="127.0.0.1";
    if(argc<2)
    {
        cout << "Usage :- mtsclient [file1] [file2] [file3] ....\r\n";
        return 0;
    }
               
    WSADATA wsaData;
    struct hostent *hp;
    unsigned int addr;
    struct sockaddr_in server;
    int wsaret=WSAStartup(0x101,&wsaData);
    if(wsaret)
        return 0;
    SOCKET conn;
    conn=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(conn==INVALID_SOCKET)
        return 0;
               
    if(inet_addr(servername)==INADDR_NONE)
    {
        hp=gethostbyname(servername);
    }
    else
    {
        addr=inet_addr(servername);
        hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
    }
    if(hp==NULL)
    {
        closesocket(conn);
        return 0;
    }
    server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
    server.sin_family=AF_INET;
    server.sin_port=htons(20248);
    if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
    {
        closesocket(conn);
        return 0; 
    }
    char buff[512];
    int z;
    z=recv(conn,buff,512,0);
    buff[z]=0;
               
    strcpy(buff,"auth passwd\r\n");
    send(conn,buff,strlen(buff),0);
               
    z=recv(conn,buff,512,0);
    buff[z]=0;
               
               
    for(int j=1;j<argc;j++)
    
        sprintf(buff,"file %s\r\n",argv[j]);
        send(conn,buff,strlen(buff),0);
                   
        CFile f;
        char *fname;
        char fname2[256];
        if(!(fname=strrchr(argv[j],'\\')))
            strcpy(fname2,argv[j]);
        else
            strcpy(fname2,fname+1);
        cout << fname2 << " has been saved.\r\n";
        f.Open(fname2,CFile::modeCreate | CFile::modeWrite);
        bool first=true;
        bool second=false;
        while(true)
        {     
            z=recv(conn,buff,128,0);
            if(z==SOCKET_ERROR)
            {
                cout << "\r\n\r\nsocket error socket error socket error\r\n";
                break;
            
            if(second)
            {
                if(NoFile(buff,128)<128)
                {
                    cout << "File " << argv[j] << " not found on server\r\n";
                    break;
                }
                second=false;
            }
            if(first)
            {
                if(NoFile(buff,128)<128)
                {
                    cout << "File " << argv[j] << " not found on server\r\n";
                    break;
                }
                first=false;
                second=true;
            }
                       
            int b;
            if((b=EndFile(buff,z))<z)
            {     
                f.Write(buff,b);
                cout << fname2 << " has been saved.\r\n";
                break;
            }
            f.Write(buff,z);
        
        f.Close();
    }
    closesocket(conn);
    WSACleanup();
    return 0;
               
}
int EndFile(char *buff, int len)
{
    int pos=len;
    for(int u=0;u<(len-4);u++)
    {
        if(buff[u]=='#')
            if(buff[u+1]=='F')
                if(buff[u+2]=='i')
                    if(buff[u+3]=='l')
                        if(buff[u+4]=='e')
                        {
                            pos=u;
                            break;
                        }
    }
    return pos;
}
int NoFile(char *buff, int len)
{
    int pos=len;
    for(int u=0;u<(len-4);u++)
    {
        if(buff[u]=='!')
            if(buff[u+1]=='F')
                if(buff[u+2]=='i')
                    if(buff[u+3]=='l')
                        if(buff[u+4]=='e')
                        {
                            pos=u;
                            break;
                        }
    }
    return pos;
}
0
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7618次
    • 积分:113
    • 等级:
    • 排名:千里之外
    • 原创:2篇
    • 转载:9篇
    • 译文:0篇
    • 评论:2条
    文章分类
    文章存档
    最新评论