TcpSocket的基本框架用法

 1 #define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 #include "osapi/osapi.h"
 6 //客户端
 7 int main()
 8 {
 9     // 打开Socket
10     OS_TcpSocket client_sock;
11     client_sock.Open();
12 
13     // 连接服务器
14     OS_SockAddr serv_addr("127.0.0.1", 9555);
15     if(    client_sock.Connect( serv_addr ) < 0)
16     {
17         printf("无法连接服务器!\n");
18         return -1;
19     }
20 
21     char buf[1024];
22 
23     // 发送请求
24     strcpy(buf, "help me");
25     int n = strlen(buf);
26     client_sock.Send(buf, n);
27 
28     // 接受应答
29     n = client_sock.Recv(buf, sizeof(buf));
30     buf[n] = 0;
31     printf("Got: %s \n", buf);
32 
33     // 关闭Socket
34     client_sock.Close();
35     return 0;
36 }
 1 #define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
 2 #include <stdio.h>
 3 #include "osapi/osapi.h"
 4 #include "TcpConn.h"
 5 //服务器 main.cpp
 6 int main()
 7 {
 8     OS_TcpSocket serv_sock ;
 9     // (1): 占用端口号
10     serv_sock.Open(OS_SockAddr(9555), true);
11 
12     // (2): 监听
13     serv_sock.Listen();
14 
15     while(1)
16     {
17         OS_TcpSocket work_sock;
18         if(serv_sock.Accept(&work_sock) < 0)
19         {
20             break;
21         }
22 
23         // 新建一个线程,处理该client的请求
24         TcpConn* conn = new TcpConn(work_sock);
25         conn->Run();
26     }
27 
28 
29     return 0;
30 }
 1 #define _CRT_SECURE_NO_WARNINGS /* VS2013,2015需要这一行 */
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 #include "TcpConn.h"
 6 //服务器 TcpConn.cpp
 7 TcpConn::TcpConn(OS_TcpSocket work_sock)
 8 {
 9     m_WorkSock = work_sock;
10 }
11 
12 TcpConn::~TcpConn()
13 {
14 
15 }
16 
17 int TcpConn::Routine()
18 {
19     // 为client提供服务
20     char buf[1024];
21 
22     // 接收客户的请求
23     int n = m_WorkSock.Recv(buf, 1024);
24     buf[n] = 0;
25     printf("客户请求: %s \n", buf);
26     
27     // 应答客户
28     strcpy(buf, "yes, ok");
29     n = strlen(buf);
30     m_WorkSock.Send(buf, n);
31 
32     // 关闭socket
33     m_WorkSock.Close();
34     
35     return 0;
36 }
 1 #ifndef _TCP_CONN_H
 2 #define _TCP_CONN_H
 3 
 4 #include "osapi/osapi.h"
 5 //服务器 TcpConn.h
 6 /* TcpConn:
 7    用一个线程来维护Client - WorkingSocket之间的通话连接
 8 */
 9 
10 class TcpConn : public OS_Thread
11 {
12 public:
13     TcpConn(OS_TcpSocket work_sock);
14     ~TcpConn();
15 
16 private:
17     virtual int Routine();
18 
19 private:
20     OS_TcpSocket m_WorkSock;
21 
22 };
23 
24 
25 
26 
27 #endif

 

posted on 2017-12-30 23:27  Doctor_uee  阅读(539)  评论(0)    收藏  举报

导航